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 url = "https://fruits-api.netlify.app/graphql" 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.
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.