Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Automating REST API Validation Using Python

Tech May 17 3

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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.