Skip to main content

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

Project description

FastAPI Mock

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

Installation

Install the package using pip:

pip install fastapi-mock

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

Usage

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

Let's define our FastAPI application:

from fastapi import FastAPI
from fastapi_mock import MockMiddleware, MockException
from pydantic import BaseModel

app = FastAPI()

app.add_middleware(MockMiddleware)  # add middleware as class, not instance


class ResponseModel(BaseModel):
    message: str


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

In the above code, we define a FastAPI application, add the MockMiddleware to handle the MockExceptions, and define a GET endpoint at /mock-endpoint. When the endpoint function is called, it raises a MockException 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.

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 MockMiddleware, MockException
from pydantic import BaseModel, ConfigDict

app = FastAPI()

app.add_middleware(MockMiddleware)


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():
    raise MockException(ResponseModel)

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"
}

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 MockMiddleware, MockException
from pydantic import BaseModel, Field

app = FastAPI()

app.add_middleware(MockMiddleware)


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():
    raise MockException(ResponseModel)

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 MockMiddleware, MockException, ExampleProvider
from pydantic import BaseModel
from faker import Faker # pip install faker

app = FastAPI()
fake = Faker()

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


class ResponseModel(BaseModel):
    message: str


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

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

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

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.2.3.tar.gz (5.7 kB view details)

Uploaded Source

Built Distribution

fastapi_mock-0.2.3-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi_mock-0.2.3.tar.gz
  • Upload date:
  • Size: 5.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.6.1 CPython/3.11.6 Windows/10

File hashes

Hashes for fastapi_mock-0.2.3.tar.gz
Algorithm Hash digest
SHA256 db5ecbe71e309921832390fd9eb5ef0fb617b495cda4a5af138ff03ac7d21d44
MD5 42c17bd2db44621870b9541f59c68e94
BLAKE2b-256 a1083d9d58542741626705c54297fb2d92fe7e4255c8691f0d58e89201e68301

See more details on using hashes here.

File details

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

File metadata

  • Download URL: fastapi_mock-0.2.3-py3-none-any.whl
  • Upload date:
  • Size: 6.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.6.1 CPython/3.11.6 Windows/10

File hashes

Hashes for fastapi_mock-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 f174a2d8f88006ef4d652d35e0f6ad102331f3387450c4acb229ac8729c3a289
MD5 a6d51080db6520bb9dc5e6eef303b25d
BLAKE2b-256 4c818102814b81c73930ef2184f7cd203e7668fc8138f1e05325d9ae3f31cd51

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