Search code examples
pythonjsonresponseassert

assert JSON response


i have an python API call, and the server response is coming to me as JSON output.

How can I assert that the "status" from this output is 0 for example:

def test_case_connection():
    req = requests.get_simple(url=Server.MY_SERVER, params=my_vars)
    assert req["status"]="0"

is what i've tried.

The response is looking like:

{"status" : 0, ......}

error i got is:

TypeError: 'Response' object has no attribute '__getitem__'

Solution

  • If you simply need to check that the request was successful, using request.status_code will do the trick:

    def test_case_connection():
        req = requests.get_simple(url=Server.MY_SERVER, params=my_vars)
        assert req.status_code == 200
    

    If you want instead to check for the presence of a specific key-value pair in the response, you need to convert your response payload from json to a dict:

    import json
    
    def test_case_connection():
        req = requests.get_simple(url=Server.MY_SERVER, params=my_vars)
        data = json.loads(req.content)
        assert data["status"] == "0"
    

    If you are using the Requests library you can avoid converting json manually by using its builtin json decoder.