How to validate Rest API with Python Pytest

Let’s move another step toward API testing In the previous tutorial, we have learned about API and End to End API testing using pytest. in this tutorial, we will be validating REST API using pytest. Already created API we will be tested and its contents will be matched with the help of a JSON file. if the contents got matched the test case will get passed.

Prerequisites

  • Install requests
  • Install pytest

validate Rest API with Python Pytest

  • Create a python file with the name test_valid_api.py. In the python file import requests and pytest module.
  • Define a function test_get() in the response variable to get a response of the given input URL.
  • Create another JSON file to store data with the name response.json.
  • Declare another variable response_body to take JSON data as input.
  • By using the assert() function check JSON data and the URL data.
test_valid_api.py
import pytest
import requests
def test_get():
     response = requests.get("http://api.zippopotam.us/us/90210")
     response_body = response.json()
     assert response_body["country"] == "United States"

In this, we have matched country data with the data present in the response.json with the help of the assert function provided by the pytest framework.

response.json
{
    "post code": "90210",
    "country": "United States",
    "country abbreviation": "US",
    "places": [
        {
            "place name": "Beverly Hills",
            "longitude": "-118.4065",
            "state": "California",
            "state abbreviation": "CA",
            "latitude": "34.0901"
        }
    ]
}

Here is the output of the above code and the test case passed successfully. similarly, we can generate test cases for different data and match that with a response.json file.

Thus in this tutorial, we have learned how to validate REST API in python using the pytest automation framework.