Skip to main content

A utility for FastAPI that allows you to create mock endpoints quickly and easily.

Project description

FastAPI Mock

A utility for FastAPI that allows you to create mock endpoints quickly and easily.

Overview

Installation

Install the package using pip:

pip install fastapi-mock

NOTE: FastAPI Mock requires Python 3.11+ and FastAPI working with Pydantic 2.

Usage

Return example instead of NotImplementedError

Here, we'll explore how to use FastAPI Mock by creating a FastAPI application, adding middleware, and raising NotImplementedError. Note that we'll be using the MockMiddleware class from the FastAPI Mock.

Let's define our FastAPI application:

from fastapi import FastAPI
from fastapi_mock import MockUtilities
from pydantic import BaseModel

app = FastAPI()

# just create an instance of MockUtilities and pass FastAPI app as argument to it. It will add exception handlers to
# the app automatically.
MockUtilities(app, return_example_instead_of_500=True)


class ResponseModel(BaseModel):
    message: str


@app.get("/mock-endpoint", status_code=200)
def mock() -> ResponseModel:
    # instead of ResponseModel, you can use any type annotation that is supported by FastAPI Mock.
    raise NotImplementedError()

In the above code, we define a FastAPI application, add the MockMiddleware to handle the exception, and define a GET endpoint at /mock-endpoint. When the endpoint function is called, it raises a NotImplementedError with ResponseModel set as the response model and 200 as the status code.

If you hit the endpoint /mock-endpoint, you'll see the mock data: just

{
  "message": "Hello, World ❤️"
}

NOTE: FastAPI Mock can process not only basic types, but list, tuple, set, dict, enum.Enum generic types and UnionTypo too. Also, it will resolve response models recursively, so you can define nested models.

Return example Instead of HTTP 500 Error

It also can replace HTTP 500 error with the example. To enable this feature, just pass return_example_instead_of_500=True to the MockUtilities constructor.

from fastapi import FastAPI
from fastapi_mock import MockUtilities
from pydantic import BaseModel

app = FastAPI()

MockUtilities(app, return_example_instead_of_500=True)


class ResponseModel(BaseModel):
    message: str


@app.get("/mock-endpoint")
def mock() -> ResponseModel:
    my_infinity = (
        1 / 0
    )  # raise ZeroDivisionError, then will be converted it to HTTP 500 error
    # in FastAPI ExceptionMiddleware and handled by FastAPI Mock
    return ResponseModel(message=f"UFO is real! and infinity is {my_infinity}")

Advanced Usage

Now we'll look at a more advanced usage of FastAPI Mock, including defining examples in the response model's JSON schema, utilizing field examples and defaults, configuring middleware with the custom provider for int and str types.

Examples in JSON Schema

FastAPI Mock will choose a random example from the examples list in the response model's JSON schema.

Let's try it out:

from fastapi import FastAPI
from fastapi_mock import MockUtilities
from pydantic import BaseModel, ConfigDict

app = FastAPI()

MockUtilities(app)


class ResponseModel(BaseModel):
    message: str

    model_config = ConfigDict(
        json_schema_extra={
            "examples": [{"message": "My name is (chka-chka, Slim Shady) - Eminem"}]
        }
    )


@app.get("/mock-endpoint")
def mock() -> ResponseModel:
    raise NotImplementedError()

The default status code is 200, so we don't need to specify it. Now, if you hit the endpoint /mock-endpoint, you'll see the mock data:

{
  "message": "My name is (chka-chka, Slim Shady) - Eminem"
}

Or you can define examples in route decorator:

from fastapi import FastAPI
from fastapi_mock import MockUtilities
from pydantic import BaseModel

app = FastAPI()

MockUtilities(app)


class ResponseModel(BaseModel):
    message: str


@app.get(
    "/mock-endpoint",
    openapi_extra={
        "examples": [{"message": "My name is (chka-chka, Slim Shady) - Eminem"}]
    },
)
def mock() -> ResponseModel:
    raise NotImplementedError()

PRIORITY: The examples from the route decorator have higher priority than the examples from the response model.

Field Examples and Defaults

FastAPI Mock will iterate through the fields in the response model and choose a random example (or default) from the field info.

Here's an example:

from fastapi import FastAPI
from fastapi_mock import MockUtilities
from pydantic import BaseModel, Field

app = FastAPI()

MockUtilities(app)


class ResponseModel(BaseModel):
    field_with_examples: str = Field(examples=["I", "Love", "Python"])
    field_with_default: str = Field(default="I ❤️ Python")
    field_with_default_factory: str = Field(default_factory=lambda: "I ❤️ Python\n" * 3)


@app.get("/mock-endpoint")
def mock() -> ResponseModel:
    raise NotImplementedError()

Now, if you hit the endpoint /mock-endpoint, you'll see the mock data:

{
  "field_with_examples": "Love",
  "field_with_default": "I ❤️ Python",
  "field_with_default_factory": "I ❤️ Python\nI ❤️ Python\nI ❤️ Python\n"
}

PRIORITY: The examples from the JSON schema have higher priority than the field examples. Moreover, the field examples have higher priority than the field defaults.

Custom Provider

FastAPI Mock uses the constant examples for str, random examples for int and float, bool by default. However, you can configure the middleware to use your own provider for any of basic types.

For example, let's configure the middleware to use the faker library for str type:

from fastapi import FastAPI
from fastapi_mock import MockUtilities, ExampleProvider
from pydantic import BaseModel
from faker import Faker  # pip install faker

app = FastAPI()
fake = Faker()

MockUtilities(
    app,
    example_provider=ExampleProvider(
        providers={
            str: lambda: fake.sentence()
        }
    )
)


class ResponseModel(BaseModel):
    message: str


@app.get("/mock-endpoint")
def mock() -> ResponseModel:
    raise NotImplementedError()

Now, if you hit the endpoint /mock-endpoint, you'll see the random mock data:

{
  "message": "Some random sentence from faker."
}

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_mock-0.3.3.tar.gz (6.1 kB view details)

Uploaded Source

Built Distribution

fastapi_mock-0.3.3-py3-none-any.whl (7.1 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_mock-0.3.3.tar.gz.

File metadata

  • Download URL: fastapi_mock-0.3.3.tar.gz
  • Upload date:
  • Size: 6.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.10.12 Linux/6.5.0-15-generic

File hashes

Hashes for fastapi_mock-0.3.3.tar.gz
Algorithm Hash digest
SHA256 ca4d56e818a665ad29920b793b48e60b3f13f7884226990af66d56f7daba34b5
MD5 126d360b38ed7bd02e0e31e6802c985d
BLAKE2b-256 6efa58ec09558b9e5001d296d9a3b7e22f92024a509841e1ff2f655475ff4d30

See more details on using hashes here.

File details

Details for the file fastapi_mock-0.3.3-py3-none-any.whl.

File metadata

  • Download URL: fastapi_mock-0.3.3-py3-none-any.whl
  • Upload date:
  • Size: 7.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.10.12 Linux/6.5.0-15-generic

File hashes

Hashes for fastapi_mock-0.3.3-py3-none-any.whl
Algorithm Hash digest
SHA256 c8e6c66b9bf2a79916f1237b9da32b1426ae1567e50f6dcdc72f70a9be9260d4
MD5 35ebdd477274666c33b88e9a37900b92
BLAKE2b-256 cbf61f47a918a7afcb5f7466f79d1b85b6bf9d5be007aa647022f9030ff54590

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page