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 andUnionTypo
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file fastapi_mock-0.2.2.tar.gz
.
File metadata
- Download URL: fastapi_mock-0.2.2.tar.gz
- Upload date:
- Size: 5.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.6.1 CPython/3.11.6 Windows/10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 690d8834867a69506151b00e8f7aba0575b7bb11200ccbe8100ab23c91c03a3c |
|
MD5 | 0b96643605e3e1ce825a344f441f4b3f |
|
BLAKE2b-256 | d221e4877ea88d3c8bce87aa0ecc9bee88c6f10560129270000cf000a58030cb |
File details
Details for the file fastapi_mock-0.2.2-py3-none-any.whl
.
File metadata
- Download URL: fastapi_mock-0.2.2-py3-none-any.whl
- Upload date:
- Size: 6.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.6.1 CPython/3.11.6 Windows/10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5c6f6c21e7b4865325b85db39c751d6eed245ffe100abb49454fca96e427d87c |
|
MD5 | bf5e799d7f1d82e8fb573e1d3bd19fa9 |
|
BLAKE2b-256 | 660b3b307d590ee418ed403101ceafeb5940428c464d41930c228864b3a6cfa6 |