Skip to content

How to Mock External APIs in Python Tests

DodaTech 2 min read

In this tutorial, you'll learn about How to Mock External APIs in Python Tests. We cover key concepts, practical examples, and best practices.

The Problem

Your test calls requests.get("https://api.example.com/data") and either hits the real API (slow, flaky, rate-limited) or fails when offline. Tests should be fast, isolated, and deterministic. Mocking replaces external dependencies with fake objects that return controlled responses. A test suite that makes real API calls takes minutes instead of seconds and breaks on network issues.

Quick Fix

1. Patch at the usage location

from unittest.mock import patch
import myapp

def test_get_user():
    mock_response = {"id": 1, "name": "Alice"}

    with patch("myapp.requests.get") as mock_get:
        mock_get.return_value.json.return_value = mock_response
        mock_get.return_value.status_code = 200
        result = myapp.get_user(1)

    assert result["name"] == "Alice"

Patch where the function is used (myapp.requests.get), not where it's defined (requests.get).

2. Use side_effect to simulate errors

def test_api_timeout():
    with patch("myapp.requests.get") as mock_get:
        mock_get.side_effect = TimeoutError("Connection timed out")
        result = myapp.get_user(1)

    assert result["error"] == "timeout"

side_effect can be an exception, a list (returned item by item on successive calls), or a callable.

3. Decorator syntax

@patch("myapp.requests.get")
def test_get_user(mock_get):
    mock_get.return_value.status_code = 200
    mock_get.return_value.json.return_value = {"id": 1}
    result = myapp.get_user(1)
    assert result["id"] == 1

Decorators apply bottom to top — the one nearest the function is patched first.

4. Mock HTTP with the responses library

pip install responses
import responses

@responses.activate
def test_external_api():
    responses.add(
        responses.GET,
        "https://api.github.com/repos/psf/requests",
        json={"name": "requests", "stars": 50000},
        status=200,
    )
    result = myapp.get_repo("psf/requests")
    assert result["stars"] == 50000

The responses library intercepts at the HTTP level, so you don't worry about import paths.

5. Verify mock calls

with patch("myapp.requests.get") as mock_get:
    myapp.get_user(1)

mock_get.assert_called_once_with("https://api.example.com/user/1")

Use assert_called_once_with, assert_called, call_count, or call_args to validate API call behavior.

6. Create a reusable mock with pytest fixtures for cleaner tests

import pytest
from unittest.mock import patch

@pytest.fixture
def mock_api():
    with patch("myapp.requests.get") as mock_get:
        mock_get.return_value.status_code = 200
        mock_get.return_value.json.return_value = {"status": "ok"}
        yield mock_get

def test_health_check(mock_api):
    result = myapp.check_health()
    assert result["status"] == "ok"

This combines mocking with pytest fixtures for cleaner, reusable test setup across multiple test functions. The fixture handles setup and teardown of the mock automatically.

7. Mock file I/O for testing without real files

from unittest.mock import mock_open, patch

def test_read_config():
    mock_data = "key=value\nname=test"
    with patch("builtins.open", mock_open(read_data=mock_data)):
        result = myapp.read_config("config.ini")
    assert result["name"] == "test"

Mock file operations to test code that reads or writes files without creating actual filesystem entries.

Prevention

  • Always patch at the usage location, not the definition
  • Use autospec=True to catch method signature mismatches
  • Use responses or requests-mock for complex HTTP scenarios
  • Never let tests make real network calls — mock all external services
  • Test both success and failure paths (timeout, 500, 404)
  • Combine mock with pytest fixtures for reusable test infrastructure
  • Use mock_open for testing file-based operations without touching the filesystem
  • Use assert_called_once_with to verify the exact arguments passed to a mocked function

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro