Verify GET API returns correct user data
Preconditions (2)
✅ Expected Result: Response status code is 200, and response body contains user ID 123 and user name 'John Doe'
import unittest import requests class TestGetUserAPI(unittest.TestCase): def setUp(self): self.url = "https://api.example.com/users/123" def test_get_user(self): try: response = requests.get(self.url) except requests.exceptions.RequestException as e: self.fail(f"API request failed: {e}") self.assertEqual(response.status_code, 200, "Expected status code 200") try: data = response.json() except ValueError: self.fail("Response is not valid JSON") self.assertIn('id', data, "Response JSON should contain 'id'") self.assertEqual(data['id'], 123, "User ID should be 123") self.assertIn('name', data, "Response JSON should contain 'name'") self.assertEqual(data['name'], 'John Doe', "User name should be 'John Doe'") if __name__ == '__main__': unittest.main()
The setUp method sets the API URL to keep the test clean and reusable.
The test method test_get_user sends a GET request to the API endpoint using requests.get. It catches exceptions to fail the test if the API call fails.
Assertions check that the status code is 200, meaning success.
Then it parses the JSON response and asserts the presence and correctness of the id and name fields.
Clear assertion messages help understand failures.
This test is independent and can be run repeatedly without side effects.
Now add data-driven testing with 3 different user IDs and expected names
status_code.response.status_code == 200 uses the correct attribute and syntax.import requests
response = requests.get('https://api.example.com/data')
print(response.json()['status']){"status": "success", "data": []}?['status'] returns the string "success" without quotes in print output.response = requests.post('https://api.example.com/login', data={'user': 'admin', 'pass': '1234'})
assert response.status_code = 200response.status_code to 200.Pass the test and this pattern moves unknown