In this article, we will be understanding how to write GET and POST requests to GRAPHQL APIs using the Python request module. Dealing with GraphQL API is a bit different compared to the simple REST APIs. We have to parse in a query that involves parsing the GraphQL queries in the request body.
What are Requests in Python
Requests is a python package/library which helps in working with HTTP requests using Python. We can very conveniently parse the body, headers, and other parameters to a request using methods provided by the requests library like, GET, PUT, POST, DELETE, etc. Using the requests module we will be parsing the queries to a GraphQL API.
What is GraphQL API In Python
GraphQL API is a query language for fetching data from a database. It has a different approach than traditional REST APIs. Using GraphQL API, we can fetch the only required information, this avoids the drawbacks of under fetching and over fetching compared to the REST APIs. This type of API allows us to fetch very fine-tuned data in a defined schema so that the application can consume it, only the data which is required will be fetched using the GraphQl queries to the API.
Setting up requests in Python
For this article, we will be using a public open API called the Fruits API, using the mentioned instructions, we can locate the query explorer and play around with the queries. You can also try your own API or any other open GraphQL API for your understanding.
Step 1:
To set up requests, we need to install requests in your local development environment. You can either use a virtual environment or install the package globally(not recommended). So, we’ll first set up the virtual environment and install the requests package in that environment.
pip install virtualenv
pip install requests
Step 2:
This will install the virtual environment package in python globally, so we can use it to create virtual environments on our system.
virtualenv venv
The above command will create a virtual environment in the current directory with the name venv you can name whatever you like.
Now, we also need to activate the environment, so if any packages are installed in the session they are stored or installed in this virtual environment and not globally. To do the activation of the virtual environment, we need to run the activate file located in the venv folder.
This command is different for Linux/macOS and Windows:
For Windows: venv\Scripts\activate
For Linux/macOS: source venv/bin/activate
Now, we can now create scripts and utilize this library for our aim which is to send get/post requests to a GraphQL API.
GET method using Python requests
We can send a GET request to the given GraphQL API with the get method provided in the requests library which we imported. Here due to the design of the API we have to use the POST method to fetch the results but it would depend on the API, we will dive into that later.
So, we have to get the query for fetching the details of the Fruit in this case. We can use the given schema like fruit followed by the id of it and parse in the attributes which we want to fetch, In this case, we are fetching the scientific name and tree_name but that can be any other attributes or all attributes from the given set of schema.
We have to parse the query to the JSON body, to do that we will call the request.post method which will post the query and return us the data. Here, the post method takes a few arguments like the URL to fetch and the JSON body to parse. We will parse the URL which we defined earlier as the first argument and then follow it by the JSON which will be a JSON object with a key query and will pass the query body in it. This will be stored in a variable for later use.
Python3
# we have imported the requests module import requests # defined a URL variable that we will be # using to send GET or POST requests to the API body = """ { fruit(id: 14) { scientific_name tree_name } } """ response = requests.post(url = url, json = { "query" : body}) print ( "response status code: " , response.status_code) if response.status_code = = 200 : print ( "response : " , response.content) |
Output:
Here, we can see that the query has returned the data with the specified attributes that are scietific_name and tree_name which were parsed in the query. This is GraphQL that is why we can get the exact data that is required of us. We can access the status_cide from the response object and the returned content using the content attribute.
Now, we also need to look at other GraphQL API which behaves a bit differently than the current API which was about Fruits. The API is Star Wars API which we will see can fetch the results with a GET request. The following API can be accessed from the link.
Python3
import requests body = """ query Query { allFilms { films { title } } } """ response = requests.get(url = url, json = { "query" : body}) print ( "response status code: " , response.status_code) if response.status_code = = 200 : print ( "response : " , response.content) |
Output:
Here we have used the GET method for fetching the data. The query is different compared to the previous example since the API is also different. The parameters parsed have remained the same format but the key changes are just the values of variables like URL and the body query. This query will also return the desired outcome if we use a POST method as follows:
response = requests.post(url=url, json={"query": body})
So, every API which uses GraphQL can be a bit different in terms of its usage, so we have to get around a bit to find which methods are suited well here.
POST method using Python requests
We can also post data to a GraphQl API using the requests library. We simply have to follow the schema and parse the data correctly. We are using the Fruit API again to post the data to it. So, we have a different type of schema, instead, we have a mutation to write instead of a query. We follow up the documentation to the right to get the schema.
We can now write up the schema and parse the attributes which we want to return after the mutation has been saved i.e. the POST request has been made, we will parse the required data.
Here, we are creating a mutation with the attribute name and the value which we want to assign so as the key-value map. After the mutation, we query the attributes which we want, here we are querying the attributes like id, scientific_name, tree_name, fruit_name, and origin. But these can be any other attributes or all attributes depending on the requirement.
Python3
# POST Request import requests body = """ mutation { addFruit( id: 1 scientific_name: "mangifera" tree_name: "mangifera indica" fruit_name: "Mango" family: "Anacardiaceae" origin: "India" description: "Mango is yellow" bloom: "Summer" maturation_fruit: "Mango" life_cycle: "100" climatic_zone: "humid" ) { id scientific_name tree_name fruit_name origin } } """ response = requests.post(url = url, json = { "query" : body}) print ( "response status code: " , response.status_code) if response.status_code = = 200 : print ( "response : " ,response.content) |
Output:
The POST method is used in the above script for posting the data so the requests.post method as previously said takes in a couple of arguments like URL and JSON, it also takes more arguments but is optional and dependent on the request we are making.
UPDATE method using Python requests
Similar to POST requests we can use the Update/PUT method to update specific or all fields in the schema. Here as well we need to create a mutation schema as previously. We will make the key-value maps for the attribute name and assign value to it. Thereafter we can mention the attributes we wish to fetch from the query after the update has been successful.
We have used the post method again to update the attributes defined earlier, we have followed the schema in the documentation.
Python3
# Update/ POST Request import requests body = """ mutation { updateFruit( id: 1 scientific_name: "mangiferaa" tree_name: "mangifera indicaa" fruit_name: "Mangooo" family: "Anacardiaceae" origin: "Indiana" description: "Mango is green" bloom: "Summer" maturation_fruit: "Mango" life_cycle: "101" climatic_zone: "humid" ) { id scientific_name tree_name fruit_name description } } """ response = requests.post(url = url, json = { "query" : body}) print ( "response status code: " , response.status_code) if response.status_code = = 200 : print ( "response : " , response.content) |
Output:
Here, we have updated the fruit attributes, using the updateFruit mutation, we have assigned the values and parsed the mutation. For the specific design of the API, you might also try the requests.update method to update the record if the post method does not work.
DELETE method using Python requests
We can even use the delete option to delete a record from the database with the GraphQl API using requests. We will again have to use the post method to delete the record. For further operations, you might also need the requests.delete method to delete the record using the GraphQL API. We have used the Delete Fruit mutation which takes in the parameter which is the id of the fruit further we also can fetch the desired attributes but we will return the values as null since they are deleted.
Python3
# DELETE Request import requests body = """ mutation{ deleteFruit(id: 3){ fruit_name scientific_name tree_name } } """ response = requests.post(url = url, json = { "query" : body}) print ( "response status code: " , response.status_code) if response.status_code = = 200 : print ( "response : " , response.content) |
Output:
So, this is how we delete the object from the database using the GraphQL API. The parameters passed to the post method function like the URL of the API and the body which will contain the mutation query.