September 12, 2018

Testing Rest API Responses

I have been developping a REST API at work using Flask, and wanted to test the response I got.

I started by testing directly the raw response using response.data, which works for small responses. As soon as you want to make it dynamic, it becomes a nightmare. Let’s say we start with the following test

# Bad idea
def test_response_string():
    response = client.get("/test")
    assert response.status_code == 200
    assert response.data == '{"key1": "value1", "key2": "value2"}'

Now, with just this test, adding a value or modifying it would be easy. But add other tests, or try to modify values…

To solve this, one solution is to decode the data received from the API, and directly compare the decoded data with some expected values. To do this, it is possible to use the response.json attribute which returns a decoded data structure from the response when its mimetype is application/json.

# Better idea
def test_response():
    expected_dict = dict(
        key1="value1",
        key2="value2"
    )
    response = client.get("/test")
    assert response.status_code == 200
    assert response.json == expected_dict

This way, you can also use a tempate element and just modify some of its fields. Very useful in case of complicated structures, and much clearer in my opinion.

This is, the option I like the most for now. Do you see an other one for this?

Copyright Marin Gilles 2019-2022