Python API Testing Examples Using requests, unittest, pytest, and jsonschema
This article provides a series of Python code examples demonstrating how to perform API automation testing tasks—including GET and POST requests, authentication, file uploads, redirects, unit testing with unittest and pytest, response mocking with responses, and response schema validation with jsonschema—offering practical guidance for backend testing.
Example 1: GET request using requests
import requests
response = requests.get('https://api.example.com/data')
print(response.status_code)
print(response.json())Output example:
200
{'status': 'success', 'data': {...}}Example 2: POST request using requests
import requests
import json
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'content-type': 'application/json'}
response = requests.post('https://api.example.com/endpoint', data=json.dumps(payload), headers=headers)
print(response.status_code)
print(response.text)Output example:
201
{"message": "Resource created"}Example 3: HTTP authentication with requests
import requests
response = requests.get('https://api.example.com/protected', auth=('username', 'password'))
print(response.status_code)
print(response.json())Output example:
200
{'message': 'Access granted'}Example 4: File upload with requests
import requests
files = {'file': open('example.txt', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)
print(response.status_code)
print(response.text)Output example:
200
{"filename": "example.txt"}Example 5: Handling redirects with requests
import requests
response = requests.get('http://redirect.example.com', allow_redirects=True)
print(response.url)
print(response.status_code)Output example:
https://final.example.com
200Example 6: Unit test with unittest framework
import unittest
import requests
class TestAPI(unittest.TestCase):
def test_get_request(self):
response = requests.get('https://api.example.com/data')
self.assertEqual(response.status_code, 200)
if __name__ == '__main__':
unittest.main()Output example:
..
----------------------------------------------------------------------
Ran 1 test in 0.001s
OKExample 7: Test case with pytest
import requests
import pytest
def test_post_request():
payload = {'key1': 'value1'}
response = requests.post('https://api.example.com/endpoint', data=payload)
assert response.status_code == 201Run test: pytest -v test_api.py
Output example:
test_api.py::test_post_request PASSEDExample 8: Mocking HTTP responses with responses library
import responses
import requests
@responses.activate
def test_mock_response():
responses.add(responses.GET, 'https://api.example.com/data', json={'status': 'ok'}, status=200)
response = requests.get('https://api.example.com/data')
assert response.json()['status'] == 'ok'Output example: (no direct output, assertion passes)
Example 9: Combining pytest with responses
import pytest
import responses
import requests
@responses.activate
def test_mocked_endpoint():
responses.add(responses.POST, 'https://api.example.com/endpoint', json={'message': 'Mocked'}, status=200)
response = requests.post('https://api.example.com/endpoint')
assert response.json()['message'] == 'Mocked'Run test: pytest -v test_api.py
Output example:
test_api.py::test_mocked_endpoint PASSEDExample 10: Validating response structure with jsonschema
import requests
import jsonschema
schema = {
"type": "object",
"properties": {
"status": {"type": "string"},
"data": {"type": "object"}
},
"required": ["status", "data"]
}
def validate_response(response):
try:
jsonschema.validate(instance=response.json(), schema=schema)
print("Response is valid.")
except jsonschema.exceptions.ValidationError as err:
print("Invalid response:", err)
validate_response(requests.get('https://api.example.com/data'))Output example:
Response is valid.These examples illustrate how to use Python for a variety of API automation testing tasks, from simple GET/POST requests to authentication, file uploads, redirects, unit testing, response mocking, and schema validation, providing practical guidance for backend testing workflows.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.