1. 程式人生 > 程式設計 >GitHub GraphQL API v4 使用

GitHub GraphQL API v4 使用

本文講解GitHub GraphQL API v4 的簡單使用方法

認證

要與GitHubCraphQL伺服器通訊,需要現有可用的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刪除

參考連線

GitHub API graphql