API testing involves testing the application programming interfaces (APIs) directly and as part of integration testing to determine if they meet expectations for functionality, reliability, performance, and security. Since APIs lack a GUI, API testing is performed at the message layer. API testing is critical for automating testing because APIs now serve as the primary interface to application logic and because GUI tests are difficult to maintain with the short release cycles and frequent changes commonly used with Agile software development and DevOps.
In this blog, we will demonstrate how you can design an automation framework for API testing using Python.
Pre-requisites
- Working knowledge of Python scripting
- Working knowledge of API under test
- PyCharm IDE
- PyTest
Setting up project
First, we will need to create a new Python project with PyCharm. If you are already aware of how to create Python Project with PyCharm, please move to the next section. Or you can refer to this guide about how to set up your first Python project with PyCharm :
https://www.jetbrains.com/help/pycharm/creating-and-running-your-first-python-project.html
Writing test case
As now you already have set up your Python project with Pycharm, let’s create a new Python file where we will add our test cases.
Please create a new Python file in your project. Let’s name it “test_apitest.py”. Notice the “test_” in your file name. This is as per the rules for PyTest. We will be running our tests using Python’s inbuilt testing framework called PyTest. PyTest picks all those python files in your project which start with “test_” for test execution.
In “test_apitest.py” file, our first statement would be :
import requests
“requests” is Python’s inbuilt module which is used to send HTTP requests to a server. We will be using this module to send requests to our API and record the response.
Now, for this tutorial, we will be using a sample test API available online: https://reqres.in/api
We will be sending requests to the endpoints defined in this API.
Please copy and paste the following code into your “test_apitest.py” file :
import requests def test_api_get(): resp = requests.get("https://reqres.in/api/users?page=2") assert (resp.status_code == 200), "Status code is not 200. Rather found : " + str(resp.status_code) for record in resp.json()['data']: if record['id'] == 4: assert record['first_name'] == "Eve",\ "Data not matched! Expected : Eve, but found : " + str(record['first_name']) assert record['last_name'] == "Holt",\ "Data not matched! Expected : Holt, but found : " + str(record['last_name']) def test_api_post(): data = {'name': 'John', 'job': 'QA'} resp = requests.post(url="https://reqres.in/api/users", data=data) data = resp.json() assert (resp.status_code == 201), "Status code is not 201. Rather found : "\ + str(resp.status_code) assert data['name'] == "John", "User created with wrong name. \ Expected : John, but found : " + str(data['name']) assert data['job'] == "QA", "User created with wrong job. \ Expected : QA, but found : " + str(data['name'])
Import requests
Using this statement, we are importing Python’s requests module in our project.
resp = requests.get(“https://reqres.in/api/users?page=2”)
This statement is the part of test_api_get() method which is one of our test cases to test the GET method of API under test. Requests.get() method sends an HTTP GET request to the given URL and returns the response object which contains all response data from the GET request and saves it to the “resp” variable.
assert (resp.status_code == 200), “Status code is not 200. Rather found : ” + str(resp.status_code)
assert is used in PyTest format to put an assertion for a condition. The condition here is to check the response code of the GET request. We can fetch the retrieved response code by using “resp.status_code”. Here we are checking if the returned response code is 200 and if not we will print a message for failed assertion.
for record in resp.json()[‘data’]:
Here we are converting our response object to a JSON syntax using resp.json() method. And then navigating the json using its entities to find the data we want to put an assertion on. The next few lines are various assertions that we have used to verify the response data.
resp = requests.post(url=”https://reqres.in/api/users”, data=data)
This statement is the part of test_api_post() method which is a test case to test the POST method of API under test. Requests.post(URL, data) method is used to send an HTTP POST request to the given URL with attached JSON data. And response object will be recorded to the resp variable.
data = resp.json()
Here we are converting our response object to JSON data and storing the resultant JSON to the data variable. The next few statements are assertions that we have applied to respond JSON data.
Also Read: QA Automation Testing Services
Running the test cases
Running the test cases using Pytest is very simple and easy. You just have to navigate to your project’s root directory using the command line (CMD) and run the following command
> pytest
This command will start executing all test files which start with “test_” and all the methods inside these files which start with “test_”. This is how pytest works. Wait for the execution. Once the test cases are executed, you will see an output like this :
========================== test session starts ======================== platform win32 -- Python 3.7.3, pytest-4.6.3, py-1.8.0, pluggy-0.12.0 rootdir: <your project path here> plugins: html-1.20.0, metadata-1.8.0 collected 2 items test_apitest.py .. [100%] ============================ 2 passed in 3.50 seconds =================
This means your 2 test cases have passed successfully. You can now add your own test cases and assertions to automate your API test cases.
Hope this article helps you to get started with API automation testing using Python. Please share your comment below for any concerns.
Happy testing!