0
0
PyTesttesting~15 mins

Testing with external services in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify user data retrieval from external API
Preconditions (2)
Step 1: Send a GET request to https://api.example.com/users/123
Step 2: Receive the JSON response containing user details
Step 3: Verify the response status code is 200
Step 4: Verify the response JSON contains 'id' equal to 123
Step 5: Verify the response JSON contains 'name' and 'email' fields
✅ Expected Result: The API returns status 200 and JSON with correct user id, name, and email fields
Automation Requirements - pytest
Assertions Needed:
Response status code is 200
Response JSON 'id' equals 123
Response JSON contains 'name' key
Response JSON contains 'email' key
Best Practices:
Use requests library to call external API
Use pytest fixtures for setup if needed
Handle possible connection errors gracefully
Avoid hardcoding URLs by using constants
Keep tests independent and repeatable
Automated Solution
PyTest
import requests
import pytest

API_URL = "https://api.example.com/users/123"

@pytest.fixture

def get_user_data():
    try:
        response = requests.get(API_URL, timeout=5)
        response.raise_for_status()
        return response
    except requests.RequestException as e:
        pytest.skip(f"Skipping test due to connection error: {e}")


def test_user_data_retrieval(get_user_data):
    response = get_user_data
    assert response.status_code == 200, f"Expected status 200 but got {response.status_code}"
    data = response.json()
    assert data.get('id') == 123, f"Expected user id 123 but got {data.get('id')}"
    assert 'name' in data, "Response JSON missing 'name' field"
    assert 'email' in data, "Response JSON missing 'email' field"

The code uses requests to call the external API URL defined as a constant API_URL. A pytest fixture get_user_data handles the GET request and skips the test if the API is unreachable or returns an error.

The test function test_user_data_retrieval uses this fixture to get the response, then asserts the status code is 200. It parses the JSON and checks the id is 123 and that name and email keys exist. This keeps the test clear, independent, and handles external service issues gracefully.

Common Mistakes - 4 Pitfalls
Hardcoding the API URL inside the test function
Not handling connection errors or timeouts
Not checking the response status code before parsing JSON
Using print statements instead of assertions
Bonus Challenge

Now add data-driven testing with 3 different user IDs: 123, 456, and 789

Show Hint