December 29, 2021

Using Python Requests to Query GraphQL

Since I didn't see any good tutorial after a bit of googling, I decided I will write up a quick tutorial on my own, so anyone searching for it, can find it here.

Using Python Requests to Query GraphQL

Since I didn't see any good tutorial after a bit of googling (I admit, I was being lazy and was looking for some fast inspiration when putting together the Computational Magic documentation), I decided I will write up a quick tutorial on my own, so anyone searching for it, can find it here.

As you can see, it is fairly easy to do. As an example, I am using our Computational Magic Summary API to summarise a string for this demo, and i am also using a custom header in order to supply an API key.

import requests
 
url = "https://beta.eu-north.computational-magic.com/api/v1"

headers = {'x-api-key': 'INSERT YOUR API KEY HERE!'}
 
query = """{summary(input: "INSERT YOUR LONG STRING HERE.")}"""

response = requests.post(url, headers=headers, json={'query': query})
print(response.status_code)
print(response.text)

But lets get into the why: while the first half of the code should be pretty self explanatory, it gets more tricky when we come to the query and the variable called response, where we store they query response. The query itself is defined as a string that encapsulates the request; for readability I am not inserting a long string in the place where that is supposed to be.

query = """{summary(input: "INSERT YOUR LONG STRING HERE.")}"""

I am using the triple quotes to denote the string as the query itself also contains quotes and this allows me to skip escaping those (not even sure if the query would work in that case).

Next up, I am defining the response. Here it is important to choose requests.post as opposed to requests.get which a REST API might require, as we have to post the query to the endpoint for it to be received (this is done via the URL and URL parms on REST).  

response = requests.post(url, headers=headers, json={'query': query})

Another important aspect is the requirement to not use data, but instead use json as the body of the request and define it in the format {'query': query} to ensure that it is transmitted in the JSON structure that the endpoint expects.

As you can see, it is not hard to use the requests module in python to query a GraphQL API, just a few minor things to be aware of.