Skip to main content

fastmock

FastMock framework, mock your FastAPI APIs

Test Coverage Package version


Documentation: https://tpemeja.github.io/fastmock

Source Code: https://github.com/tpemeja/fastmock


FastMock is a Python framework designed to mock FastAPI APIs based on response models.

Key features of this project include:

  • Ease of Use: Simply add the middleware to start mocking your APIs.
  • Flexibility: Mocking can be customized through various parameters, such as activation, data generation, length, status codes, and more.
  • Modularity: The package includes default functions to retrieve mocking parameters from API declarations to request headers. However, all these functions can be modified, allowing you to create your own custom functions.
  • Fault Injection: Simulate latency and failures per-route or via request header, so you can test how your client handles a slow or unreliable API without writing any extra code.
  • Request Validation: Path, query, header, cookie, and body parameters are validated against the endpoint's declared types by default, returning the same 422 a real FastAPI implementation would — without ever calling your real Depends(...) dependencies.
  • Reproducible Responses: A response is a pure function of the request, so the same call returns the same data across refreshes, restarts and machines. Demos stop reshuffling and integration tests can assert on a literal payload.
  • Plausible Data: A field named country holds a country, not a random string. Where a schema can't express an invariant, hand fastmock your own factory.

Requirements

This package is build to be used with FastAPI, please learn on to use it on their well documented website - FastAPI Documentation

To mock an API, you need to describe the API using FastAPI's decorator key responses.

For example:

@app.get("/",
         status_code=status.HTTP_200_OK,
         responses={
             status.HTTP_200_OK: {"model": list[int]},
             status.HTTP_404_NOT_FOUND: {"model": str}
         })

Installation

$ pip install fastmock

---> 100%

Or, if you use uv:

$ uv add fastmock

---> 100%

Example

Create it

  • Create a file main.py with:
from fastapi import FastAPI, status
from pydantic import BaseModel

from fastmock.decorator import FastMockDecorator
from fastmock.middleware import FastMockMiddleware

app = FastAPI()
app.add_middleware(FastMockMiddleware)


mock = FastMockDecorator()

class Customer(BaseModel):
    first_name: str
    last_name: str
    city: str
    country: str
    is_active: bool | None = None


@app.get("/",
         status_code=status.HTTP_200_OK,
         responses={
             status.HTTP_200_OK: {"model": dict[str, str]}
         })
def read_root():
    return {"Hello": "World"}


@mock(element_size=3)
@app.get("/customers",
         status_code=status.HTTP_200_OK,
         responses={
             status.HTTP_200_OK: {"model": list[Customer]}
         })
def read_customers():
    return []
  • Start the server with uvicorn main:app

Check it

Open your browser at http://127.0.0.1:8000/customers.

You will see the JSON response as:

[
  {
    "first_name": "Robert",
    "last_name": "Foster",
    "city": "Reynoldsfurt",
    "country": "Luxembourg",
    "is_active": null
  },
  {
    "first_name": "Morgan",
    "last_name": "Wong",
    "city": "Charlesborough",
    "country": "Grenada",
    "is_active": null
  },
  {
    "first_name": "Maureen",
    "last_name": "Dodson",
    "city": "Cookhaven",
    "country": "Swaziland",
    "is_active": null
  }
]

Refresh the page and you will see exactly the same response: mock data is reproducible by default.

You just created an API using FastAPI that:

  • Return value generated from defined response model
  • Generate values that match what the field names mean, not just their types
  • Modify output list size using decorator
  • Return the same data for the same request, every time

How does this compare to other FastAPI mocking libraries?

A couple of other projects cover similar ground. Here's how fastmock differs:

fastmock fastapi-mock fastapi-mock-middleware
Trigger Decorator / middleware config raise NotImplementedError(), or catches a 500 Middleware, per unimplemented route
Per-route status code override ✅ – –
Runtime overrides via request headers ✅ – –
Configurable data retrieval precedence chain ✅ – –
Multiple examples, randomly chosen – ✅ –
Fault injection (delay / failure rate) ✅ – –
Request validation (real FastAPI-shaped 422s) ✅ – –
Reproducible responses (same request, same data) ✅ – –
Field-name-aware data generation ✅ – –
Pydantic 2 ✅ ✅ –
Actively maintained ✅ ✅ ❌ (last commit 2024)

fastapi-mock is a great fit if you want the absolute lowest-friction way to stub an endpoint you haven't implemented yet — no decorator, no config, just raise NotImplementedError(). fastmock trades a little more setup for per-route and per-request control over data shape, status codes, and failure modes, which matters once you're mocking for QA, staging, or demo environments rather than just a placeholder.

Inspiration

  • A project idea that came from my use of FastAPI by tiangolo, the GitHub project inspired me for the structure and documentation of this project.
  • Ideas and code for data generation with Faker inspired by NiyazNz in the fastapi-mock-middleware project.

Contributing

This project uses uv for dependency management. To set up a development environment, run the tests, or cut a release, see the Contributing guide.

License

This project is licensed under the terms of the MIT license.

Metadata

Release files for fastmock 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastmock 0.2.0
File Size Uploaded
fastmock-0.2.0.tar.gz 701.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fastmock 0.2.0
File Interpreter ABI Platform
fastmock-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 718.5 kB

Release files / fastmock-0.2.0.tar.gz

Download URL fastmock-0.2.0.tar.gz
Size 701.5 kB
Tags Source
SHA-256 checksum
How to use checksums
251124000d77465303f7a014b5d184bd2c822c8814e939c4d7aa19f7008fe73a
BLAKE2b-256 checksum
How to use checksums
0b6ac22b34b9ed175af94be9bb0cee6be3719fa9788c07ba1eed59e2a5ee6211
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / fastmock-0.2.0-py3-none-any.whl

Download URL fastmock-0.2.0-py3-none-any.whl
Size 17.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5959ae4e37cb362920415055b36aa04ad6268a8ae75cdfbee8df760a72546389
BLAKE2b-256 checksum
How to use checksums
430e14f61a3331e88447e316bc3337840a1f5ca59e712092f858731063fb5a63
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page