How to consume the Github GraphQL API using Python?

26k views Asked by At

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
    }
  }
}
4

There are 4 answers

3
Yasss On

Graphene is for building GraphQL APIs not for consuming them.

Did you see that: https://github.com/graphql-python/gql ?

It's a GraphQL client for Python.

Hope that's helpful.

3
sreenivas On

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)
1
Paul Verest On

Exactly for GitHub, there is an example on using the Github GraphQL API with Python 3

https://gist.github.com/gbaman/b3137e18c739e0cf98539bf4ec4366ad

(check link as it has a lot of comments including better code for authentication)

# An example to get the remaining rate limit using the Github GraphQL API.

import requests

headers = {"Authorization": "Bearer YOUR API KEY"}


def run_query(query): # A simple function to use requests.post to make the API call. Note the json= section.
    request = requests.post('https://api.github.com/graphql', json={'query': query}, headers=headers)
    if request.status_code == 200:
        return request.json()
    else:
        raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))

        
# The GraphQL query (with a few aditional bits included) itself defined as a multi-line string.       
query = """
{
  viewer {
    login
  }
  rateLimit {
    limit
    cost
    remaining
    resetAt
  }
}
"""

result = run_query(query) # Execute the query
remaining_rate_limit = result["data"]["rateLimit"]["remaining"] # Drill down the dictionary
print("Remaining rate limit - {}".format(remaining_rate_limit))

And there are many Python GraphQL client libraries:

Official list is at https://graphql.org/code/#python
(just scroll down, client libraries are after server libraries)

0
Eran Kampf On

As previous answers mentioned, calling GraphQL is as simple has making a POST request with the query string. However, if you're on Python3 want something more advanced that'll also verify your queries during build and generate typed data-class response classes for you check out the new GQL library: https://github.com/ekampf/gql