How to Mock requests.get in Python
Mock requests.get with unittest.mock to test code that makes HTTP calls without hitting the network.
pip install requests
Python code
18 linesimport requests
from unittest.mock import Mock, patch
def fetch_user_data(user_id):
response = requests.get(f"https://api.example.com/users/{user_id}")
return response.json()
def process_user(user_id):
mock_response = Mock()
mock_response.json.return_value = {"id": user_id, "name": "Alice", "age": 30}
with patch("requests.get", return_value=mock_response):
data = fetch_user_data(user_id)
return f"User {data['name']} is {data['age']} years old"
if __name__ == "__main__":
print(process_user(123))
Output
User Alice is 30 years old
How it works
The patch context manager replaces requests.get with a mock that returns a crafted response object. Mock().json.return_value sets the value returned from the .json() method, allowing the code to process data as if it came from a real API. This isolates the function from network failures and latency, making tests fast and deterministic. The mock is automatically restored after the with block exits, so no global state leaks into other tests.
Common mistakes
- Patching 'fetch_user_data' instead of 'requests.get', which misses the point of isolation.
- Forgetting to set json.return_value — the mock returns a Mock object that fails when .json() is called.
- Using a real network call in tests, making them slow and flaky.
- Not using patch as a context manager, leading to manual cleanup and potential leaks.
Variations
- Use patch.object(requests, 'get') to be more explicit about the targeted attribute.
Real-world use cases
- Unit testing a service layer that calls external APIs, ensuring consistent behavior without network dependence.
- Simulating different API responses (success, error, timeout) by varying the mock return value.
- Running integration tests in CI where external endpoints are unavailable or rate-limited.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.