How to Mock requests.get in Python

Mock requests.get with unittest.mock to test code that makes HTTP calls without hitting the network.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 13 views 0 copies

Requires third-party packages — install first
pip install requests

Python code

18 lines
Python 3.9+
import 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

stdout
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

  1. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Testing & modern typing

Related tutorials and quizzes for this topic.