LoginSignup
11
4

More than 3 years have passed since last update.

Github GraphQL API v4

Last updated at Posted at 2019-06-05

Github GraphQL API v4 って?

公式ドキュメント
https://developer.github.com/v4/

文字通り、GraphQLベースのAPIです。
GraphQLの詳細については他の投稿でも解説されておりますので、割愛します。

Github GraphQL API v4 を使ってみる

今回はGithubから色んな情報を持ってきたいと思います。
GraphQLを利用の際は、
https://developer.github.com/v4/explorer/
こちらからログインをして、GUIベースのものからJSONを入力するケースと、cURLコマンド等でリクエストするケースがあります。
※事前にGithubのアカウントから、 Personal access tokens を発行しておく必要があります。

以下は、特定のプルリクエストに投稿されたコメントを取得するものです。

a095e0b8-8020-1797-5deb-e470c7a072af.png

$ curl -H "Authorization: token [発行したtoken]" -X POST -d '
> {
> "query":"query{repository(owner:\"[ユーザー名]\", name:\"[リポジトリ名]\"){pullRequest(number:1){comments(first:100){nodes{bodyText}}}}}"
> }
> ' https://api.github.com/graphql
{"data":{"repository":{"pullRequest":{"comments":{"nodes":[{"bodyText":"テストコメント1"},{"bodyText":"テストコメント2"},{"bodyText":"テストコメント3"}]}}}}}
$ 

Github GraphQL API v4 のJSON構成を調べるためには

https://developer.github.com/v4/query/
こちらを参考に組み立てて行くのですが、結構クセが凄いんじゃなドキュメントです。

先を例に解説していくと、まずは特定のリポジトリの情報が知りたいので、

repository (Repository)
Lookup a given repository by the owner and repository name.

こいつを指定し、対象をさらに絞っていくのでリンクが貼られている Repository にアクセスします。
GitHub Enterprise 利用時は複数のOrganizationがあると思うので、こちらから掘り下げて行きます。

organization (Organization)
Lookup a organization by login.

リポジトリからさらに絞り混む条件が新たに表示されます。
リポジトリに登録されているプルリクエストの情報が知りたいので、次にこれを掘り下げて行きます。
※プルリクエストの番号を指定します。

pullRequest (PullRequest)
Returns a single pull request from the current repository by number.

プルリクエストからさらに絞り混む条件が新たに表示されます。
プルリクエスト内のコメント情報を取得したいので、次にこれを掘り下げて行きます。
※取得するコメント数を指定します。

comments (IssueCommentConnection!)
A list of comments associated with the pull request.

次に絞り込む条件では、以下を利用していきます。
nodes -> bodyText

nodes ([IssueComment])
A list of nodes.
bodyText (String!)
The body rendered to text.

という感じで、JSONを組み立てて行きます。

サンプル

プルリクエスト内で更新されたファイルを取得
{
  repository(owner: "[ユーザー名]", name: "[リポジトリ名]") {
    pullRequest(number: 1) {
      files(first: 100) {
        nodes {
          path
        }
      }
    }
  }
}
プルリクエストの一覧(タイトル)を取得
{
  repository(owner: "[ユーザー名]", name: "[リポジトリ名]") {
    pullRequests(first: 100) {
        nodes {
        title
      }
    }
  }
}

プルリクエストを指定する場合は pullRequest で番号を指定するのですが、プルリクエストの一覧情報を取る場合は pullRequests で指定します。この辺りがクセが凄い(と個人的に)思っています。
他にも並び順を指定したり、取得数等を一旦変数で置いて変数の値を指定して取得する方法等があり、なかなか奥深い機能です。

11
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
4