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 url = "https://fruits-api.netlify.app/graphql" 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.
GET and POST Requests in GraphQL API using Python requests
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.