How to consume the Github GraphQL API using Python?

Vaibhav Singh picture Vaibhav Singh · Aug 30, 2017 · Viewed 14.1k times · Source

I want to access details from Github using Github GraphQl v4 API. I found Graphene library, but I'm not sure how to authenticate with a personal access token in Python.
I tried to search on Google but couldn't found any example. It's Python library that can create graphical schema's and are not for consuming them, I tried with `requests' but failed. How can i authenticate and can find list of repositories?

I have used Github GraphQl explorer to find list of repositories via this code:

viewer {
repositories(first: 30) {
  totalCount
  pageInfo {
    hasNextPage
    endCursor
  }
  edges {
    node {
      name
    }
  }
}

Answer

sreenivas picture sreenivas · Sep 18, 2017

Unlike rest, graphql has only one end point. You just need to do a POST with your query as a json object. You should provide your api_token you get from github as part of the headers.

import requests

url = 'https://api.github.com/graphql'
json = { 'query' : '{ viewer { repositories(first: 30) { totalCount pageInfo { hasNextPage endCursor } edges { node { name } } } } }' }
api_token = "your api token here..."
headers = {'Authorization': 'token %s' % api_token}

r = requests.post(url=url, json=json, headers=headers)
print (r.text)