API Navigator Logo

Python Test API with pytest

Author: Newtum

This guide shows how to write API tests using `pytest`, a popular and powerful testing framework for Python. We'll use the `pytest-mock` plugin to simulate API calls.

Testing with Pytest and Mocks

`pytest` makes testing simple and scalable. The `mocker` fixture (from `pytest-mock`) allows us to patch `requests.get` and control the API response within our test function.

import requests
# Assuming pytest and pytest-mock are installed

# A simple function that interacts with an API
def get_todo_title(todo_id):
    response = requests.get(f"https://jsonplaceholder.typicode.com/todos/{todo_id}")
    if response.status_code == 200:
        return response.json()['title']
    return None

def test_get_todo_title_success(mocker):
    # Mock the requests.get call
    mock_response = mocker.Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {'title': 'delectus aut autem'}
    mocker.patch('requests.get', return_value=mock_response)

    # Call the function and assert the result
    title = get_todo_title(1)
    assert title == 'delectus aut autem'

def test_get_todo_title_not_found(mocker):
    # Mock a 404 response
    mock_response = mocker.Mock()
    mock_response.status_code = 404
    mocker.patch('requests.get', return_value=mock_response)

    title = get_todo_title(999)
    assert title is None

# To run, save as 'test_api.py' and run 'pytest' in your terminal.
print("This code demonstrates pytest test cases for an API call.")