Package: fastapi-mock
FastAPI MockA utility for FastAPI that allows you to create mock endpoints quickly and easily.OverviewInstallationUsageReturn example instead ofNotImplementedErrorReturn example Instead of HTTP 500 ErrorAdvanced UsageExamples in JSON SchemaField Examples and DefaultsCustom ProviderContributingInstallationInstall the package usingpip:pipinstallfastapi-mockNOTE:FastAPI Mock requires Python 3.11+ and FastAPI working with Pydantic 2.UsageReturn example instead ofNotImplementedErrorHere, we'll explore how to useFastAPI Mockby 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:fromfastapiimportFastAPIfromfastapi_mockimportMockUtilitiesfrompydanticimportBaseModelapp=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)classResponseModel(BaseModel):message:str@app.get("/mock-endpoint",status_code=200)defmock()->ResponseModel:# instead of ResponseModel, you can use any type annotation that is supported by FastAPI Mock.raiseNotImplementedError()In the above code, we define a FastAPI application, add theMockMiddlewareto handle the exception, and define aGETendpoint at/mock-endpoint. When the endpoint function is called, it raises aNotImplementedErrorwithResponseModelset as the response model and200as 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, butlist,tuple,set,dict,enum.Enumgeneric
types andUnionTypotoo. Also, it will resolve response models recursively, so you can define nested models.Return example Instead of HTTP 500 ErrorIt also can replace HTTP 500 error with the example. To enable this feature, just passreturn_example_instead_of_500=Trueto theMockUtilitiesconstructor.fromfastapiimportFastAPIfromfastapi_mockimportMockUtilitiesfrompydanticimportBaseModelapp=FastAPI()MockUtilities(app,return_example_instead_of_500=True)classResponseModel(BaseModel):message:str@app.get("/mock-endpoint")defmock()->ResponseModel:my_infinity=(1/0)# raise ZeroDivisionError, then will be converted it to HTTP 500 error# in FastAPI ExceptionMiddleware and handled by FastAPI MockreturnResponseModel(message=f"UFO is real! and infinity is{my_infinity}")Advanced UsageNow 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
forintandstrtypes.Examples in JSON SchemaFastAPI Mock will choose a random example from theexampleslist in the response model's JSON schema.Let's try it out:fromfastapiimportFastAPIfromfastapi_mockimportMockUtilitiesfrompydanticimportBaseModel,ConfigDictapp=FastAPI()MockUtilities(app)classResponseModel(BaseModel):message:strmodel_config=ConfigDict(json_schema_extra={"examples":[{"message":"My name is (chka-chka, Slim Shady) - Eminem"}]})@app.get("/mock-endpoint")defmock()->ResponseModel:raiseNotImplementedError()The default status code is200, 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:fromfastapiimportFastAPIfromfastapi_mockimportMockUtilitiesfrompydanticimportBaseModelapp=FastAPI()MockUtilities(app)classResponseModel(BaseModel):message:str@app.get("/mock-endpoint",openapi_extra={"examples":[{"message":"My name is (chka-chka, Slim Shady) - Eminem"}]},)defmock()->ResponseModel:raiseNotImplementedError()PRIORITY:The examples from the route decorator have higher priority than the examples from the response model.Field Examples and DefaultsFastAPI 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:fromfastapiimportFastAPIfromfastapi_mockimportMockUtilitiesfrompydanticimportBaseModel,Fieldapp=FastAPI()MockUtilities(app)classResponseModel(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")defmock()->ResponseModel:raiseNotImplementedError()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 ProviderFastAPI Mock uses the constant examples forstr, random examples forintandfloat,boolby 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 thefakerlibrary forstrtype:fromfastapiimportFastAPIfromfastapi_mockimportMockUtilities,ExampleProviderfrompydanticimportBaseModelfromfakerimportFaker# pip install fakerapp=FastAPI()fake=Faker()MockUtilities(app,example_provider=ExampleProvider(providers={str:lambda:fake.sentence()}))classResponseModel(BaseModel):message:str@app.get("/mock-endpoint")defmock()->ResponseModel:raiseNotImplementedError()Now, if you hit the endpoint/mock-endpoint, you'll see the random mock data:{"message":"Some random sentence from faker."}ContributingPublishing a new versionUpdate the version inpyproject.tomlCommit the changesCreate a new tag with the version number (e.g.git tag -a 0.1.0 -m "0.1.0")Push the tag to the repository (e.g.git push origin 0.1.0)Draft a new release on GitHub with the same version number and the release notesSetup poetry PyPi configuration (
seetutorial)Runpoetry buildRunpoetry publishAttach the built wheel to the releasePublish the releaseDone!