How to make unauthenticated requests to GitHub GraphQL API

Viewed 840

I am trying to use github graph api to make requests and grab only the details I require ie. number of stars on some public repo. An unauthenticated request to get details on a repo using V3(REST) api works fine, but it contains a million details of the repo which I don't need, I just need number of stars on the repo.

When I make following request:

query {
  repository(owner: "facebook", name: "react") {
    stargazers {
      totalCount
    }
  }
}

In javascript using fetch it responds 401 Unauthorized

fetch('https://api.github.com/graphql', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: '{ repository(owner: "facebook", name: "react") { stargazers(last: 10) { totalCount } } }' })
})
.then(res => res.json())
.then(res => console.log(res));

I need to show the data on a public website so I can't use a token from my github account to authenticate.
Is there some way to make requests without authenticating, maybe some workaround. Or is it not possible?

2 Answers

The GitHub GraphQL API requires authentication to make requests.

You can either make an equivalent REST API call and discard the information which you don't need, or have server-side code make the request with an appropriate API token and proxy that information to your frontend code.

Note that if you expect your application to make a large number of total requests to the GitHub API, you'll probably want to go the latter route and implement caching.

If you will eventually need to make more than 5,000 requests/hour, then you can make an OAuth Github App, and have each user make the request from their own browser with their own key.

Related