22

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
    }
  }
}
Vaibhav Singh
  • 1,554
  • 3
  • 13
  • 27

4 Answers4

36

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)
sreenivas
  • 2,067
  • 1
  • 19
  • 29
  • 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 me – Vaibhav Singh Oct 08 '17 at 13:36
  • @VaibhavSingh Am not sure if I got your wording correct. Mind explaining it again. – sreenivas Oct 09 '17 at 14:41
  • 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 program – Vaibhav Singh Oct 09 '17 at 16:56
9

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.

Yasss
  • 488
  • 3
  • 9
  • 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 library – Vaibhav Singh Sep 01 '17 at 17:36
  • 2
    @VaibhavSingh following the GitHub documentation (https://developer.github.com/v4/guides/forming-calls/#authenticating-with-graphql), you need to generate an access token like that https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/. Then, you have to pass your token into the `Authorization` header like that https://developer.github.com/v4/guides/forming-calls/#communicating-with-graphql. Cheers, – Yasss Sep 03 '17 at 09:35
  • 2
    @VaibhavSingh you can also use the graphical client GraphiQL https://github.com/graphql/graphiql to explore the GraphQL API and try out queries before writing them in python. Good luck ! – achedeuzot Sep 10 '17 at 10:18
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

Eran Kampf
  • 8,928
  • 8
  • 49
  • 47
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)

Paul Verest
  • 60,022
  • 51
  • 208
  • 332
  • ratelimit status is in http headers of every response, see [example](https://gist.github.com/gbaman/b3137e18c739e0cf98539bf4ec4366ad?permalink_comment_id=3926716#gistcomment-3926716) – milahu Mar 22 '23 at 11:21