REST API testing basics in Testing Fundamentals - Build an Automation Script
import unittest import requests class TestGetUserAPI(unittest.TestCase): def setUp(self): self.base_url = "https://api.example.com/users" def test_get_user_details(self): user_id = 123 url = f"{self.base_url}/{user_id}" try: response = requests.get(url) except requests.RequestException as e: self.fail(f"Request failed: {e}") self.assertEqual(response.status_code, 200, f"Expected status code 200 but got {response.status_code}") content_type = response.headers.get('Content-Type', '') self.assertIn('application/json', content_type, f"Expected Content-Type application/json but got {content_type}") try: data = response.json() except ValueError: self.fail("Response is not valid JSON") self.assertEqual(data.get('id'), user_id, f"Expected user id {user_id} but got {data.get('id')}") self.assertIn('name', data, "Response JSON missing 'name' field") self.assertIn('email', data, "Response JSON missing 'email' field") if __name__ == '__main__': unittest.main()
This test uses Python's unittest framework and the requests library to automate the manual test case.
In setUp, the base URL is defined for reuse.
The test method test_get_user_details sends a GET request to the user endpoint with ID 123.
It asserts the HTTP status code is 200, ensuring the request succeeded.
It checks the Content-Type header includes 'application/json' to confirm the response format.
The response body is parsed as JSON. If parsing fails, the test fails with a clear message.
Finally, it asserts the JSON contains the expected user ID, and the 'name' and 'email' fields exist.
Try-except blocks handle request errors and JSON parsing errors gracefully, providing clear failure reasons.
This structure keeps the test clear, independent, and easy to maintain.
Now add data-driven testing with 3 different user IDs: 123, 456, and 789