Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume the Github GraphQL API using Python?

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
    }
  }
}
like image 938
Vaibhav Singh Avatar asked Aug 30 '17 10:08

Vaibhav Singh


People also ask

How do I use GraphQL with GitHub API?

To communicate with GitHub's GraphQL API, fill in the header name with "Authorization" and the header value with "bearer [your personal access token]". Save this new header for your GraphiQL application. Finally, you are ready to make requests to GitHub's GraphQL API with your GraphiQL application.

Can we use GraphQL with Python?

Known for its ease of use and simplicity, Python is one of the most beloved general-purpose programming languages. And GraphQL, a declarative query language for APIs and server runtimes, pairs quite nicely with Python.

How do you consume GraphQL?

This takes only three steps: Identify the API you wish to consume. Identify the site containing the data you need. Make the API call using credentials that have access to the data.


4 Answers

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)
like image 102
sreenivas Avatar answered Oct 02 '22 03:10

sreenivas


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.

like image 35
Yasss Avatar answered Oct 02 '22 04:10

Yasss


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

like image 31
Eran Kampf Avatar answered Oct 02 '22 04:10

Eran Kampf


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:

  • https://github.com/graphql-python/gql (aka https://github.com/ekampf/gql)
  • https://github.com/graphql-python/gql-next
  • https://github.com/prodigyeducation/python-graphql-client

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

like image 3
Paul Verest Avatar answered Oct 02 '22 04:10

Paul Verest