Verify GET /users API returns correct user data
Preconditions (2)
✅ Expected Result: Response status code is 200 and response body JSON contains {'id': 1, 'name': 'John Doe'}
Jump into concepts and practice - no test required
import requests import pytest BASE_URL = "http://api.example.com" def test_get_user_by_id(): user_id = 1 expected_name = "John Doe" response = requests.get(f"{BASE_URL}/users/{user_id}") # Assert status code is 200 assert response.status_code == 200, f"Expected status code 200 but got {response.status_code}" data = response.json() # Assert user ID and name in response assert data.get('id') == user_id, f"Expected user id {user_id} but got {data.get('id')}" assert data.get('name') == expected_name, f"Expected user name '{expected_name}' but got '{data.get('name')}'"
This test sends a GET request to the API endpoint for user with ID 1.
We check the HTTP status code to confirm the request succeeded (200 means OK).
Then we parse the JSON response and verify the user ID and name match expected values.
Assertions include clear messages to help understand failures.
Using requests library is standard for HTTP calls in Python.
This test is simple, independent, and repeatable.
Now add data-driven testing to verify multiple user IDs and names
response.status_code.assert response.status_code == 200 is syntactically correct and checks the status code properly.def test_api_response(client):
response = client.get('/status')
data = response.json()
assert data['success'] is True
data['success'] is True, which matches the parsed value, so it passes.def test_get_user(client):
response = client.get('/user/1')
assert response.status_code = 200
assert response.json()['id'] == 1
assert response.status_code = 200 uses single '=' which is assignment, not comparison.assert response.status_code == 200.json={'name': 'book'} sends JSON properly; data= sends form data, which is incorrect here.response.status_code == 201 to check for created resource status; response.status is invalid.