Skip to main content

グローバルノードIDの利用

のほとんどのオブジェクト(ユーザ、Issue、プルリクエストなど)には、REST APIを使っても、GraphQL APIを使ってもアクセスできます。 REST API 内から多くのオブジェクトのグローバル ノード ID を検索し、GraphQL 操作でこれらの ID を使えます。 詳細については、「REST API リソースでの GraphQL API ノード ID のプレビュー」を参照してください。

メモ

REST では、グローバル ノード ID フィールドに node_id という名前が付けられます。 GraphQL では、これは node インターフェイス上の id フィールドになります。 GraphQL での "ノード" の意味をもう一度確認するには、「GraphQLの紹介」を参照してください。

グローバルノードIDを効率的に利用するには、以下の3つのステップを踏んでください。

  1. オブジェクトの node_id を返す REST エンドポイントを呼び出します。
  2. GraphQLでのそのオブジェクトの型を見つけます。
  3. そのIDと型を使い、GraphQLでダイレクトにノードのルックアップを行います。

例を見ていきましょう。

認証されたユーザーを要求する場合:

curl -i --header "Authorization: Bearer YOUR-TOKEN" https://api..com/user

認証されたユーザーの node_id を含むレスポンスが返されます。

{
  "login": "octocat",
  "id": 1,
  "avatar_url": "https://.com/images/error/octocat_happy.gif",
  "gravatar_id": "",
  "url": "https://api..com/users/octocat",
  "html_url": "https://.com/octocat",
  "followers_url": "https://api..com/users/octocat/followers",
  "following_url": "https://api..com/users/octocat/following{/other_user}",
  "gists_url": "https://api..com/users/octocat/gists{/gist_id}",
  "starred_url": "https://api..com/users/octocat/starred{/owner}{/repo}",
  "subscriptions_url": "https://api..com/users/octocat/subscriptions",
  "organizations_url": "https://api..com/users/octocat/orgs",
  "repos_url": "https://api..com/users/octocat/repos",
  "events_url": "https://api..com/users/octocat/events{/privacy}",
  "received_events_url": "https://api..com/users/octocat/received_events",
  "type": "User",
  "site_admin": false,
  "name": "monalisa octocat",
  "company": "",
  "blog": "https://.com/blog",
  "location": "San Francisco",
  "email": "[email protected]",
  "hireable": false,
  "bio": "There once was...",
  "public_repos": 2,
  "public_gists": 1,
  "followers": 20,
  "following": 0,
  "created_at": "2008-01-14T04:33:35Z",
  "updated_at": "2008-01-14T04:33:35Z",
  "private_gists": 81,
  "total_private_repos": 100,
  "owned_private_repos": 100,
  "disk_usage": 10000,
  "collaborators": 8,
  "two_factor_authentication": true,
  "plan": {
    "name": "Medium",
    "space": 400,
    "private_repos": 20,
    "collaborators": 0
  },
  "node_id": "MDQ6VXNlcjU4MzIzMQ=="
}

この例では、node_id 値は MDQ6VXNlcjU4MzIzMQ== です。 この値を使って、同じオブジェクトをGraphQLでクエリできます。

しかし、最初にオブジェクトの 種類 を把握する必要があります。 シンプルなGraphQLクエリで、この型を調べることができます。

query {
  node(id:"MDQ6VXNlcjU4MzIzMQ==") {
     __typename
  }
}

このクエリの種類—ノードを ID で見つける—は、"ダイレクト ノード ルックアップ" と呼ばれています。

このクエリを実行すると、__typenameUser になります。

種類を確認したら、インライン フラグメントを使って、その ID によってオブジェクトにアクセスし、追加のデータを返すことができます。 この例では、こちらでクエリを実行する User のフィールドを定義しています。

query {
  node(id:"MDQ6VXNlcjU4MzIzMQ==") {
   ... on User {
      name
      login
    }
  }
}

この種のクエリは、オブジェクトをグローバルノードIDでルックアップする標準的なアプローチです。

REST API または GraphQL API を使用するインテグレーションを構築する場合、API バージョン間にわたってオブジェクトを簡単に参照できるように、グローバルノード ID を保持すると良いでしょう。 REST と GraphQL の間の移行処理の詳細については、「RESTからGraphQLへの移行」を参照してください。