Using Requests to Test GraphQL in Python

No votes yet.
Please wait...

If you’re not familiar with GraphQL API, just remember that they differ from the classic REST API in the way they access information. Usually, in regular REST APIs, a user just sends a GET request to receive information with a particular resource. For example, a GET request to https://api.zippopotam.us/us/90211 retrieves a specific location associated with US zip code 90211.

In contrast, in the context of a GraphQL, the user creates a GraphQL request and sends it to the API via POST. This allows getting information from several sources (potentially, from multiple data sources) in a single, aggregated API call.

For example, if you want to receive the name of a SpaceX global company, as well as the name of its CEO and COO, you can do that by sending a GraphQL request to API of the SpaceX site – https://api.spacex.land/graphql/.

{
company {
ceo
coo
name
}
}

By doing so, you can get a response with the JSON body:

{
“data”: {
“company”: {
“ceo”: “Elon Musk”,
“coo”: “Gwynne Shotwell”,
“name”: “SpaceX”
}
}
}

As we can see in the examples, the request uses original GraphQL syntaxis but the response is in JSON. It’s good news for those who are going to use an inquiry library to test GraphQL API. Let’s see how to do it correctly.

The simplest way to create and send a GraphQL request to a particular API is to hard code the request inside the test program code as a string:
query_company_ceo_coo_name = “””

{
company {
ceo
coo
name
}
}
“””

Now, all we need to do for sending a request to GraphQL API is to develop a JSON request payload with a single element request where a request string is a value. And that’s it, there’s nothing complex here.

Also, below you can see an example of how all the described above looks like in a test using requests and pytest, complete with an assertion on the response HTTP status code to check that a test request was processed correctly:

def test_retrieve_graphql_data_should_yield_http_200():
response = requests.post(“https://api.spacex.land/graphql/”, json={‘query’: query_company_ceo_coo_name})
assert response.status_code == 200

All this is surprisingly obvious. The only thing that might be a little confusing is to hard-code each GraphQL query as lines of code as much as possible. But this is already the material of other studies.

Leave A Comment