Hackernoon logo3 new ways to mock out APIs in Python by@anthony.p.shaw

3 new ways to mock out APIs in Python

Anthony Shaw Hacker Noon profile picture

Anthony Shaw

Python Fellow, ASF Member and hacker

Getting your tests right can be crucial

In my last blog on the topic, I talked about how requests_mock can be used to mock out quick and simple responses to REST APIs.

  • Returning large responses, like CSV reports
  • Returning binary files, like images
  • Dynamically responding via callbacks

What I’ve put together is a new (beta) package for creating a simple bridge between your unit tests and the Python requests adapter API.

The package is called requests-staticmock and you can find the code at GitHub and PyPi.

It provides 3 new ways to mock out API responses.

Pattern 1 : Mocking out an API to a set of files

Consider this scenario, you want to test a class that you developed, which

In it’s simplest form, you can use a context manager to inject a static asset adapter into your requests session.

If the method does not exist, it will generate a 404 response.

Here is a more detailed example of how this could be used.

Pattern 2 : Mocking out a specific URL, but using a live instance also

In this example, you might want to mock out a particular API, but keep access to another. The Adapter injector (and the context manager pattern) support specific URLs within a session, keeping the default HTTP behaviour for URLs that do not match the pattern.

Pattern 3 : Having a test class generate the responses

This pattern gives you access to creating a shared class that has callbacks for all of the URLs you might want to test

If the method does not exist, it will generate a 404 response.


The goal of this library was to make it dead-simple to mock out HTTP APIs for a given API client in Python.

I’m looking for feedback as this is an early beta, please raise issues on GitHub with any pointers or feature ideas.


Join Hacker Noon

Create your free account to unlock your custom reading experience.