Mock an external API without testing your own mock
In this article (3 sections)
A fake that always returns whatever the application expects can make broken integration code look correct. Test both sides of the adapter contract.
Assert the call and response shape
The engineering foundations lab records a fixture request.
from engineering_cases import mock_contract_case
result = mock_contract_case()
assert result["request_asserted"] is True
assert result["response_contract_checked"] is True
assert result["calls"][0]["timeout"] == 5
assert result["network_called"] is FalseThe test checks URL and timeout, then validates status, fields and Boolean type. No API runs.
Model representative success, invalid response, timeout, throttling and server error. Keep canned payloads from provider documentation or a sanitized, approved sandbox capture. Validate them against OpenAPI/JSON Schema when available. Do not reproduce the application’s parsing logic inside the fake.
Mocks provide fast isolation; sandbox contract tests catch drift in authentication, paths and schemas. Run both at different cadences and identify which evidence is offline.
The FDE for Freshers course uses this distinction in its API integration project.
Exercise
Inject an HTTP client into one adapter. Assert request details, add a malformed fake and a recorded contract test, then show each catches a different defect.
Continue learning
This article is part of the FDE engineering foundations sequence. Use the neighbouring tasks when you need the prerequisite or the next application.
- Review the prerequisite or neighbouring task in Use fixtures to isolate test data from production data.
- Continue with Read a stack trace and identify the failing contract.
Reference: pytest monkeypatch guidance.
Pankit Kumar has 10 years in Data Science & AI, building and shipping production systems in regulated pharma and clinical environments. He is a freelance trainer at Boston Institute of Analytics, AnalytixLabs and Scaler, and has taught this material to thousands of working professionals.
This article is part of our FDE for Freshers programme — 6–7 months. Build your engineering foundations, then take AI from discovery to delivery.
Explore FDE for Freshers