0
0
PyTesttesting~15 mins

API client testing in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify GET /users API returns correct user data
Preconditions (2)
Step 1: Send a GET request to http://api.example.com/users/1
Step 2: Check the HTTP status code of the response
Step 3: Check the response body contains user data with ID 1 and name 'John Doe'
✅ Expected Result: Response status code is 200 and response body JSON contains {'id': 1, 'name': 'John Doe'}
Automation Requirements - pytest
Assertions Needed:
Assert response status code is 200
Assert response JSON contains correct user ID and name
Best Practices:
Use requests library for HTTP calls
Use pytest fixtures for setup if needed
Keep tests independent and repeatable
Use clear and descriptive assertion messages
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
Not checking the HTTP status code before parsing JSON
Hardcoding full URLs multiple times
Not providing assertion messages
Bonus Challenge

Now add data-driven testing to verify multiple user IDs and names

Show Hint