API Navigator Logo

Python Mock API Response Example

Author: Newtum

This guide shows how to mock an API response for testing purposes using `unittest.mock`. Mocking allows you to test your application's logic without making actual network requests, which makes tests faster and more reliable.

Using `unittest.mock.patch`

We can use `@patch` as a decorator to replace `requests.get` with a `Mock` object for the duration of a test. We then configure this mock to behave like a real `requests.Response` object.

import unittest
from unittest.mock import patch, Mock
import requests

# Function we want to test
def get_user_name(user_id):
    response = requests.get(f'https://api.example.com/users/{user_id}')
    return response.json()['name']

class TestUserApi(unittest.TestCase):
    @patch('requests.get')
    def test_get_user_name(self, mock_get):
        # Setup the mock response
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = {'name': 'Mock User', 'id': 1}
        mock_get.return_value = mock_response

        # Call our function
        user_name = get_user_name(1)

        # Assert that our function processed the mocked data correctly
        self.assertEqual(user_name, 'Mock User')
        
        # We can also assert that the request was made as expected
        mock_get.assert_called_once_with('https://api.example.com/users/1')

# This would be run by a test runner like 'unittest' or 'pytest'
print("This code demonstrates how to mock an API call for a unit test.")