In the previous article, we have seen What API is, What and How API testing should be performed, and how we can test APIs using the Postman tool. We have also learnt the rest assured framework for API automation. In this post, we will explore the Python requests module and how we can perform API testing Using Python requests library.
Can Python Be Used For API Testing?
Python is a popular, high-level, object-oriented programming language with a simplified syntax and supports many libraries and frameworks.
A few reasons are listed below why Python is a good choice for API testing:
- Simple Syntax: Due to its simple syntax Python is easy to learn and use.
- Large Ecosystem: Python has a large ecosystem of libraries and frameworks that support API testing. Python supports numerous third-party libraries for making HTTP requests, handling responses, parsing data formats like JSON and XML, and validating responses.
- Multiple Protocol support: Python provides support for different protocols like HTTP, Rest, SOAP, and GraphQL.It is convenient to automate all these using a single language.
- Data manipulation and validation: It is very easy to manipulate and validate data in Python due to Python’s built-in libraries and integration with third-party libraries.
How to Automate API in Python?
Python provides several libraries that can be used for API testing. Some of them are listed below.
- Requests
- pyhttptest
- pyresttest
What is Python Requests Library?
Python Requests is a very popular and very powerful library that supports HTTP methods. It is commonly used for API testing and also supports tasks like managing cookies, sessions and authentication. This module is also widely used for web scraping.
Prerequisite:
- IDE
- Installation and configuration of Python
- End Point (API to be tested)
Installation of Python Requests Module
a) Using Pycharm IDE
- If you are using Pycharm IDE then you need to install the Request library. Execute the below command using pip.
pip install -U requests
2. Install Pytest
pytest is a Python testing framework that makes it easy to write simple unit tests as well as complex functional tests. pytest can automatically discover and run tests in the project, making it easy to organize and execute the test suite.
pip install -U pytest
3. Create a new project folder and open it in PyCharm.
4. Create a new class file and import all the dependencies as mentioned below.
import requests
import json
import pytest
b) How To Setup VSCode For Python API Testing
If you don’t have Pycharm IDE then you can use the VSCode editor to setup Python by following below mentioned steps.
- Create a new project directory and open it in VS code.
- Go to the Extensions view (
Ctrl+Shift+X
), search for “Python” and install the official Python extension by Microsoft. - Set up a virtual environment for Python.
- Open the integrated terminal in VS Code and create a virtual environment by running the following command in the terminal:
python -m venv venv
4. Activate the virtual terminal by using the below command.
source venv/bin/activate
5. Now Install the required libraries using this terminal.
pip install pytest requests
How to Use Python Requests with REST APIs
I will be using Reqres API for this tutorial.
1)Go to the project folder and Create a new file, naming it “testAPI.py”.
2)Import the required packages.
3)Write a Script for automating GET, Post, Put and Delete calls.
1)How to Request Data With GET
The GET method is used to get the resource from the server and returns 200 if successful.
Scenario:
- Define the Endpoint.
- Send the get request.
- Verify the status code and print the response.
import requests
import json
import pytest
ENDPOINT = 'https://reqres.in/api/'
USER = 'users/2'
def test_get_endpoint():
response = requests.get(ENDPOINT+USER)
assert response.status_code==200
print(response)
pytest identifies the test case from test_name syntax, hence I have created a method test_get_endpoint().Under this method requested URL is defined.
The requests. get() method hits the provided endpoint and saves the response in a variable. We are using the “assert” keyword from the pytest module to validate the response code.
2)Sending Post Request with Python Requests
The post method is used to create new resources on the server. It returns 201 or 200 after the successful request.
Requests Library Post Syntax
requests.post(URL, data=[data], json=[json], headers=[headers], cookies=[cookies], files=[files] arguments)
- Specify the data type that needs to be sent in the request.
- Call requests.post() method with the targeted Endpoint.
- Provide request payload.
- Validate the status code.
import requests
import json
import pytest
ENDPOINT = 'https://reqres.in/api/'
def test_post_request():
payload = {
"email": "[email protected]",
"password": "cityslickaa"
}
response = requests.post(ENDPOINT + "login",json=payload)
assert response.status_code==200
json_response =json.loads(response.text)
token = json_response["token"]
print(token)
The test_post_request() method is created to perform the post operation and validate that a resource is created successfully. The json parameter automatically sets the “Content-Type” header to “application/json” and serializes the payload as JSON.
“json. loads()” method of the JSON module parses the response string and converts it into a Python dictionary that helps in accessing JSON easily within the code.
3)Put Request with Python
Put requests are used to update or create a new resource on the server.
Scenario:
- Send a post request to create a new resource.
2. Validate the response code.
3. Verify that the resource is updated.
4. Send a put request to update the resource.
5. Verify the status code.
6. Validate response JSON for updated data.
POST request for resource creation
import requests
import json
import pytest
ENDPOINT = 'https://reqres.in/api/'
def test_createUser_request():
payload = {
"name": "morpheus01",
"job": "leader"
}
response = requests.post(ENDPOINT + "users",json=payload)
assert response.status_code==201
json_response =json.loads(response.text)
id = json_response["id"]
if "id" in json_response:
print(id)
else:
print("not found")
A new user is created with the name ‘morpheus01’ having a job as a leader. Now we want to modify the job for this user. We will use put request to update the job as a businessman.
PUT request to modify the resource
def test_updateUser_request():
payload = {
"name": "morpheus01",
"job": "businessman" //Job value is changed
}
response = requests.put(ENDPOINT + "users/2",json=payload)
assert response.status_code==200
json_response =json.loads(response.text)
job= json_response["job"]
print(job)
assert response.json()["job"] == "buisnessman" //Should pass
assert job == "buisnessman" //Should pass
assert json_response.get('job') == 'leader'//Should fail as job is updated
With the above method, I have created a dictionary payload containing updated user data, including a modified job value and sent the put request to update the user details for the user with ID 2, using the provided payload.
Once the put method is successful, the next step is to assert whether the job is updated or not. In the above code, I have added 3 assert statements to check the updated response.
Handling Authentication
Many APIs require authentication to access protected resources. Python Requests supports various authentication methods, including basic authentication, API keys, OAuth, and more. For example, to authenticate using an API key, you can include it in the request headers:
headers = {'Authorization': 'Bearer YOUR_API_KEY'}
response = requests.get('https://api.example.com/data', headers=headers)
4)Delete with Python Requests Module
Delete verb is used to remove the resource from the server. Delete requests can return response codes like 200,202,204 or 404.
Scenario:
- Send a delete request for a user having id =2
- Validate the status code.
def test_deleteUser_request():
response = requests.delete(ENDPOINT + "users/2")
assert response.status_code==204
We have completed the CRUD operation automation using the Python Requests library in this module. Refer to the complete code for this post below.
Complete Sample Code
import requests
import json
import pytest
ENDPOINT = 'https://reqres.in/api/'
USER = 'users/2'
def test_get_endpoint(): //GET Request
response = requests.get(ENDPOINT+USER)
assert response.status_code==200
print(response)
def test_createUser_request(): //POST Request
payload = {
"name": "morpheus01",
"job": "leader"
}
response = requests.post(ENDPOINT + "users",json=payload)
assert response.status_code==201
json_response =json.loads(response.text)
id = json_response["id"]
if "id" in json_response:
print(id)
else:
print("not found")
if not (id is None):
print("value is present for given JSON key")
print(id)
else:
print("value is not present for given JSON key")
def test_updateUser_request(): //PUT Request
payload = {
"name": "morpheus01",
"job": "buisnessman"
}
response = requests.put(ENDPOINT + "users/2",json=payload)
assert response.status_code==200
json_response =json.loads(response.text)
job= json_response["job"]
print(job)
assert response.json()["job"] == "buisnessman"
assert job == "buisnessman"
assert json_response.get('job') == 'leader'
def test_deleteUser_request(): //DELETE Request
response = requests.delete(ENDPOINT + "users/2")
assert response.status_code==204
Test case Execution
Test case execution using pytest is very simple and straightforward. Open the terminal, navigate to the project root folder and execute the below command.
pytest
To execute all these tests together go to the terminal and type below mentioned command.
python -m pytest -v [testFileName]
python -m pytest -v test-api.py
Pytest will start running the test cases starting with test_name. Once the execution is complete we can see the final result in the terminal.
Conclusion
In this post, we have learned about the Python Requests module and how we can perform API testing using the Python Requests module.