Skip to content


The requests-mock library is a requests transport adapter that can be preloaded with responses that are returned if certain URIs are requested. This is particularly useful in unit tests where you want to return known responses from HTTP requests without making actual calls.


pip install requests-mock


Object initialization

Select one of the following ways to initialize the mock.

As a pytest fixture

The ease of use with pytest it is awesome. requests-mock provides an external fixture registered with pytest such that it is usable simply by specifying it as a parameter. There is no need to import requests-mock it simply needs to be installed and specified as an argument in the test definition.

import pytest
import requests
from requests_mock.mocker import Mocker

def test_url(requests_mock: Mocker):
    requests_mock.get('', text='data')
    assert 'data' == requests.get('').text

As a function decorator

>>> @requests_mock.Mocker()
... def test_function(m):
...     m.get('', text='resp')
...     return requests.get('').text
>>> test_function()

As a context manager

>>> import requests
>>> import requests_mock

>>> with requests_mock.Mocker() as m:
...     m.get('', text='resp')
...     requests.get('').text

Mocking responses

Return a json

        "id": 882,
        "number": 209,
        "finished": 1591197904,
    cookies={"Id": "0"},
    headers={"id": "0"},

Multiple responses

Multiple responses can be provided to be returned in order by specifying the keyword parameters in a list.

        {'text': 'resp1', 'status_code': 300},
        {'text': 'resp2', 'status_code': 200}

Get requests history


The easiest way to test if a request hit the adapter is to simply check the called property or the call_count property.

>>> import requests
>>> import requests_mock

>>> with requests_mock.mock() as m:
...     m.get(', text='resp')
...     resp = requests.get('')
>>> m.called
>>> m.call_count

Requests history

The history of objects that passed through the mocker/adapter can also be retrieved.

>>> history = m.request_history
>>> len(history)
>>> history[0].method
>>> history[0].url