GitHub GraphQL API v4 使用
阿新 • • 發佈:2020-06-24
本文講解GitHub GraphQL API v4 的簡單使用方法
認證
要與GitHub
的 CraphQL
伺服器通訊,需要現有可用的OAuth
令牌。點此開啟建立token
頁面,完成申請。官方申請教程
GraphQL端點
GraphQL API只有一個地址為:https://api.github.com/graphql
發起請求
設定header
headers: {
Authorization: 'bearer token'
}
複製程式碼
簡單curl
請求示例
curl -H "Authorization: bearer token" -X POST -d " \
{ \
\"query\": \"query { viewer { login }}\" \
} \
" https://api.github.com/graphql
複製程式碼
在Node.js中發起請求
安裝請求客戶端
yarn add graphql-request
複製程式碼
使用示例
const { GraphQLClient } = require('graphql-request')
const endpoint = 'https://api.github.com/graphql'
const graphQLClient = new GraphQLClient(endpoint,{
headers: {
authorization: `bearer ${token}`
}
})
// 查詢指定組織下程式碼庫列表
const query = `
{
organization (login:"cyytemplate"){
repositories(first:100){
totalCount
nodes {
name
description
resourcePath
updatedAt
}
}
}
}
`
const data = await graphQLClient.request(query)
// 查詢指定組織下指定倉庫名的程式碼資料
const query = `
{
organization (login:"cyytemplate"){
repository(name:"${name}"){
name
description
resourcePath
updatedAt
}
}
}
`
const data = await graphQLClient.request(query)
複製程式碼
explorer
官方提供的線上請求工具
注意事項
不要把GitHub生成的token
編碼到程式碼中,並提交到GitHub,GitHub的安全機制,會檢查到,並立刻將該token
刪除