How to consume the Github GraphQL API using Python?
Asked Answered
E

4

23

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
    }
  }
}
Exempt answered 30/8, 2017 at 10:18 Comment(0)
I
38

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)
Inveracity answered 18/9, 2017 at 4:10 Comment(3)
Thanks for answering!! So small doubt if i want to customize my json by adding some functions with default arguments. So I will add first:10 in default argument and if i want to edit , i can override by passing first:30. I know it's a foolish question but can you help meExempt
@VaibhavSingh Am not sure if I got your wording correct. Mind explaining it again.Inveracity
Right now json is modified by us and we will get the expected result from GraphQL but if i want that i can customize the json buy passing agruments in function and can change the query according to the user. Right now it's hardcoded in the programExempt
D
10

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.

Darden answered 31/8, 2017 at 11:41 Comment(3)
Thanks for the answer. I looked into gql but how to authenticate with Github. Now, I am thinking to solve this problem by writing my own libraryExempt
@VaibhavSingh following the GitHub documentation (developer.github.com/v4/guides/forming-calls/…), you need to generate an access token like that help.github.com/articles/…. Then, you have to pass your token into the Authorization header like that developer.github.com/v4/guides/forming-calls/…. Cheers,Darden
@VaibhavSingh you can also use the graphical client GraphiQL github.com/graphql/graphiql to explore the GraphQL API and try out queries before writing them in python. Good luck !Afrikaans
B
3

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

Briton answered 31/12, 2018 at 5:9 Comment(0)
I
2

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)

Illomened answered 27/5, 2021 at 10:17 Comment(1)
ratelimit status is in http headers of every response, see exampleGomar

© 2022 - 2024 — McMap. All rights reserved.