Automating REST API Validation Using Python
API Endpoints Under Test
Consider a RESTful service managing employee records. The validation suite targets the following operations:
- GET
/staff: Retrieve all employees - POST
/staff: Add a new employee - GET
/staff/{emp_id}: Retrieve a specific employee - PATCH
/staff/{emp_id}: Modify an employee's details - DELETE
/staff/{emp_id}: Remove an employee
Dependency Installation
Ensure the HTTP client and test runner are available in the environment:
pip install requests pytest
Implementing the Validation Suite
The following implementation utilizes the built-in unittest framework. To ensure logical flow and reduce redundancy, the test cases share a created resource ID through class-level attributes.
import requests
import unittest
class ValidateEmployeeEndpoints(unittest.TestCase):
HOST = "https://api.mock.dev/staff"
@classmethod
def setUpClass(cls):
cls.shared_emp_id = None
cls.headers = {"Content-Type": "application/"}
def test_01_add_employee(self):
payload = {"first_name": "Alice", "department": "Engineering"}
resp = requests.post(self.HOST, =payload, headers=self.headers)
self.assertEqual(resp.status_code, 201)
body = resp.()
self.assertIn("emp_id", body)
ValidateEmployeeEndpoints.shared_emp_id = body["emp_id"]
def test_02_fetch_specific_employee(self):
self.assertIsNotNone(self.shared_emp_id)
url = f"{self.HOST}/{self.shared_emp_id}"
resp = requests.get(url, headers=self.headers)
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.().get("emp_id"), self.shared_emp_id)
def test_03_modify_employee(self):
self.assertIsNotNone(self.shared_emp_id)
url = f"{self.HOST}/{self.shared_emp_id}"
update_payload = {"department": "Product"}
resp = requests.patch(url, =update_payload, headers=self.headers)
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.().get("department"), "Product")
def test_04_remove_employee(self):
self.assertIsNotNone(self.shared_emp_id)
url = f"{self.HOST}/{self.shared_emp_id}"
resp = requests.delete(url, headers=self.headers)
self.assertEqual(resp.status_code, 204)
def test_05_list_all_employees(self):
resp = requests.get(self.HOST, headers=self.headers)
self.assertEqual(resp.status_code, 200)
self.assertIsInstance(resp.(), list)
if __name__ == "__main__":
unittest.main()
Executing the Suite
Save the script as api_validation.py and execute it via the command line:
python -m unittest api_validation.py
Interpreting Outcomes
A successful run yields output resembling:
.....
----------------------------------------------------------------------
Ran 5 tests in 0.450s
OK
Failures will explicitly indicate which assertion failed and the corresponding endpoint response.