> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo GitHub GraphQL API

> Guide to using the GitHub GraphQL API to fetch precise repository and workflow data, compare with REST, manage query cost and rate limits, and follow best practices.

Let’s explore how the GitHub GraphQL API can give you precise, efficient access to repository and workflow data—avoiding the extra fields and multiple requests common with the REST API.

![A presentation slide titled "GitHub GraphQL API" with a large blue teardrop-shaped graphic on the right that says "Demo." The slide is branded with a small "© Copyright KodeKloud" notice.](https://mintcdn.com/kodekloud-c4ac6d9a/TlnHw4JjIHBx3Cta/images/GitHub-Administration-Certification/Monitoring-and-Optimization/Demo-GitHub-GraphQL-API/github-graphql-api-demo-kodekloud.jpg?fit=max\&auto=format\&n=TlnHw4JjIHBx3Cta\&q=85\&s=5bab4fb467a58530e3fbe48c54b1e224)

## Why GraphQL over REST for GitHub data

REST endpoints often return large JSON payloads containing many fields you don’t need, which increases bandwidth and parsing overhead. GraphQL lets you request exactly the fields you want and compose nested data in a single request.

Key benefits:

* Select only the fields you need.
* Fetch nested related objects in one request (avoid multiple REST calls).
* Receive responses exactly shaped to your query, reducing bandwidth and parsing.

| Concern | REST | GraphQL |
| -: | :- | :- |
| Requesting only a few fields | Often returns full objects with many unused fields | Request exactly the fields you need |
| Fetching nested data | Multiple endpoints/calls (e.g., PR → commits → comments → reviews) | Single nested query returns all related data |
| Response size | Typically larger, more parsing | Smaller, tailored payload |
| Rate/cost visibility | Standard REST rate limits | Query-specific `cost` and `rateLimit` object |

## Example: REST workflow runs (problem statement)

A typical GET to list workflow runs returns many fields—even if you only care about the workflow `name` and its `status`.

HTTP request (example):

```http theme={null}
GET https://api.github.com/repos/game-devstudio/ghas-guardrail-demo/actions/runs
Authorization: Bearer ghp_4tGctcsOCu0O0ZDyMrpYtVhT35...
Accept: application/vnd.github+json
```

Truncated JSON response (example):

```json theme={null}
{
  "total_count": 40,
  "workflow_runs": [
    {
      "id": 32819140135,
      "name": "Using Reusable CI Workflow",
      "node_id": "WFR_kwLOUBTRK88AAAAHpCxWJw",
      "head_branch": "main",
      "head_sha": "8de63f5e91e37f0f07afa3da0141ff3a2ac67001",
      "path": ".github/workflows/ci.yml",
      "display_title": "Add push trigger to secrets-priority workflow",
      "run_number": 9,
      "event": "push",
      "status": "completed",
      "conclusion": "success",
      "workflow_id": 340540734
    }
  ]
}
```

If you only need `name`, `status`, and `conclusion`, the remainder of this payload is wasted. GraphQL fixes that by letting you select only the fields you want.

## GraphQL examples

Example: list organization members (name + avatar) — GraphQL:

```graphql theme={null}
query {
  organization(login: "github") {
    membersWithRole(first: 100) {
      edges {
        node {
          name
          avatarUrl
        }
      }
    }
  }
}
```

REST equivalent:

```bash theme={null}
curl -v https://api.github.com/orgs/:org/members
```

Example: fetch a pull request with commits, comments, and reviews in one nested GraphQL query:

```graphql theme={null}
{
  repository(owner: "octocat", name: "Hello-World") {
    pullRequest(number: 1) {
      commits(first: 10) {
        edges {
          node {
            commit {
              oid
              message
            }
          }
        }
      }
      comments(first: 10) {
        edges {
          node {
            body
            author {
              login
            }
          }
        }
      }
      reviews(first: 10) {
        edges {
          node {
            state
          }
        }
      }
    }
  }
}
```

Contrast with REST, which typically requires multiple calls:

```bash theme={null}
curl -v https://api.github.com/repos/:owner/:repo/pulls/:number
curl -v https://api.github.com/repos/:owner/:repo/pulls/:number/commits
curl -v https://api.github.com/repos/:owner/:repo/issues/:number/comments
curl -v https://api.github.com/repos/:owner/:repo/pulls/:number/reviews
```

## Making a GraphQL request to GitHub

Endpoint:

```http theme={null}
POST https://api.github.com/graphql
```

Typical headers:

```http theme={null}
Content-Type: application/json
Authorization: bearer ghp_XXXXxxxYYYY
Accept: */*
User-Agent: YourAppName/1.0
```

You send a JSON payload containing the GraphQL `query` (and optional `variables`). Example: request `rateLimit` plus repository default branch and the latest commit metadata:

GraphQL query:

```graphql theme={null}
query($owner: String!, $repo: String!) {
  rateLimit {
    limit
    cost
    remaining
    resetAt
  }
  repository(owner: $owner, name: $repo) {
    defaultBranchRef {
      name
      target {
        ... on Commit {
          history(first: 1) {
            nodes {
              oid
              message
              statusCheckRollup {
                state
                contexts(first: 50) {
                  nodes {
                    ... on CheckRun {
                      id
                      name
                      status
                      conclusion
                      url
                    }
                    ... on StatusContext {
                      id
                      context
                      state
                      targetUrl
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
```

Variables (JSON):

```json theme={null}
{
  "owner": "game-devstudio",
  "repo": "ghas-guardrail-demo"
}
```

Send the above GraphQL query + `variables` as the body of your POST to `/graphql`. The response will include only requested fields and a `rateLimit` object. GraphQL also returns a `cost` that indicates how many request points the query consumed.

GraphQL queries have a computed request cost. Large nested queries cost more tokens. Unauthenticated requests have much lower rate limits; you will likely hit the unauthenticated rate limit quickly for public repositories. Use an authenticated token to get higher limits and more headroom for expensive queries.

## Example: large nested query (cost demonstration)

Complex nested query against the public `kubernetes/kubernetes` repository:

```graphql theme={null}
query ComplexCostTest {
  rateLimit {
    limit
    cost
    remaining
    resetAt
  }
  repository(owner: "kubernetes", name: "kubernetes") {
    name
    description
    pullRequests(first: 100) {
      nodes {
        title
        number
        state
        author {
          login
        }
        commits(first: 10) {
          nodes {
            commit {
              oid
              message
              authoredDate
            }
          }
        }
        comments(first: 10) {
          nodes {
            body
            createdAt
            author {
              login
            }
          }
        }
      }
    }
  }
}
```

If you run this query without a token you may see an error like:

```json theme={null}
{
  "message": "API rate limit exceeded for 124.123.131.242. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)",
  "documentation_url": "https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting"
}
```

With a valid token the query will succeed but may take several seconds; the `rateLimit` object will show the `cost` used by the query.

## Best practices and summary

* Use GraphQL when you need precise control over response fields or to aggregate nested related data in a single request.
* Always monitor the `rateLimit` object and the query `cost` to avoid surprises.
* Authenticate your requests (use a PAT or app token) to increase rate limits and handle more expensive queries.
* Keep queries focused (limit `first:` values and the depth of nested selections) to reduce cost and latency.

## Links and references

* [GitHub GraphQL API documentation](https://docs.github.com/en/graphql)
* [GitHub REST API rate limiting](https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting)
* [GitHub Developer: Authenticating to the API](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#authentication)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/github-administration-certification/module/ddb3d739-d57f-4374-b851-69bb14cbeb8b/lesson/1f47ff6c-777c-4f81-a1a4-27bab8f3b2af)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.