Member-only story
How To Add Multiple Request and Response Examples in FastAPI
Level up your documentation

By reading this article, you will learn to extend the documentation of FastAPI to include multiple examples for all the requests and responses. This works for both Swagger UI and ReDoc endpoints.
For example, you will be able to achieve the following result in ReDoc:

Likewise, the same functionality is applicable for Swagger UI as well:

Previously, you had to rely on pydantic’s Field()
object or extra_schema
inside classes that inherit from BaseModel
in order to add examples to it. Besides that, you could only add a single example to either the request or response.
As of version 0.64.0, FastAPI officially supports the example
and examples
arguments for the following objects:
Body()
Path()
Query()
Cookie()
Header()
According to the official documentation:
“There’s a newer version of OpenAPI: 3.1.0, recently released. It is based on the latest JSON Schema and most of the modifications from OpenAPI’s custom version of JSON Schema are removed, in exchange of the features from the recent versions of JSON Schema, so all these small differences are reduced. Nevertheless, Swagger UI currently doesn’t support OpenAPI 3.1.0.”
The developers behind FastAPI work around the issue with some tricks to handle the compatibility as well as incompatibilities between OpenAPI, JSON Schema, and OpenAPI's 3.0.x custom version of JSON Schema.
Let’s proceed to the next section and start installing the necessary Python modules.
Setup
It is highly recommended to create a new virtual environment before you continue with the installation.