skip to content

In FastAPI, how do you add example request bodies to /docs, and how do Body(examples=...) and Body(openapi_examples=...) differ?

level: middleimportance: nice to knowfreq 18%

answer

  1. two places in the document
  2. a list inside the schema
  3. a named map beside it
  4. which one Swagger UI renders best

basics

~20 s

Field(examples=...), json_schema_extra and Body(examples=[...]) put example lists into the JSON Schema. Body(openapi_examples={...}) adds named examples with a summary and value beside the schema, which Swagger UI shows better. FastAPI validates none of them against the model.

solid answer

~30 s

FastAPI's OpenAPI 3.1 document has two homes for examples. JSON Schema examples are a plain list: `Field(examples=[...])` on a model field, `json_schema_extra` on the model, or `Body(examples=[...])` on the parameter, which places the list in the request body's schema. OpenAPI-specific examples come from `Body(openapi_examples={...})`: a dict from a name to `summary`, `description`, `value` or `externalValue`, placed on the request body's media type. FastAPI documents that Swagger UI supports the OpenAPI-specific ones better, so use `openapi_examples` to offer several named scenarios in `/docs`. The singular `example` argument is deprecated, and FastAPI does not validate any example against the model.

code

python · 33 lines
python
from typing import Annotated

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Order(BaseModel):
    sku: str = Field(examples=["LAMP-01"])
    quantity: int = 1


@app.post("/orders")
async def create_order(
    order: Annotated[
        Order,
        Body(
            openapi_examples={
                "single": {
                    "summary": "One lamp",
                    "value": {"sku": "LAMP-01", "quantity": 1},
                },
                "bulk": {
                    "summary": "A bulk order",
                    "description": "Quantities above 50 go to the warehouse queue.",
                    "value": {"sku": "LAMP-01", "quantity": 120},
                },
            }
        ),
    ],
):
    return order

go deeper

for a junior

Know that examples declared in Field() or Body() appear in /docs beside the request body, and that they do not change validation.

for a middle

Explain the two homes: a JSON Schema examples list versus the named openapi_examples map with summary and value, and why Swagger UI favours the second.

for a senior

Keep examples true as models change: they are never validated, so add a test that validates each example and treat stale examples as a documentation defect.

for a principal

Set a team convention for where examples live, field level for reuse or endpoint level for scenarios, so client developers get consistent and tested documentation.

## Why examples matter in the docs FastAPI generates an **OpenAPI** document from your path operations and serves it to **Swagger UI** at `/docs` and **ReDoc** at `/redoc`. For a request body, the generated schema tells a reader which fields exist and which are required, but not what a realistic order looks like. **Examples** fill that gap: Swagger UI shows them in the request body section, and client developers copy them. FastAPI offers several places to declare them, and they end up in two different parts of the OpenAPI document. ## Where examples can live | Where you declare it | API | Where it lands in OpenAPI | |---|---|---| | On a model field | `Field(examples=["LAMP-01"])` | the model's JSON Schema, on that property | | On the whole model | `model_config = {"json_schema_extra": {"examples": [...]}}` | the model's JSON Schema | | On a body parameter | `Body(examples=[{...}])` | the request body's JSON Schema, as an `examples` list | | On a body parameter | `Body(openapi_examples={...})` | the request body's media type, as a named `examples` map | The first three are **JSON Schema examples**: a plain list of values. The last is the **OpenAPI-specific** `examples` field: a dict from a name to an object with extra information. ## JSON Schema examples Since FastAPI 0.99.0 the generated document uses **OpenAPI 3.1.0**, which is based on JSON Schema 2020-12. That version of JSON Schema has an `examples` keyword that is just a list. FastAPI puts every example you declare with `Field(examples=...)`, `json_schema_extra` or `Body(examples=...)` into the relevant schema: - A field example describes one property and travels with the model wherever it is reused, including in response schemas. - A `Body(examples=...)` list describes this endpoint's body only, without touching the model. - The singular `example` argument still works but is **deprecated**; FastAPI's own deprecation message points to `examples`, because the singular keyword is not part of JSON Schema. ## OpenAPI-specific examples with openapi_examples OpenAPI had its own `examples` field before JSON Schema gained one, and it sits outside the schema, on the operation's request body media type. Each entry has a name and can carry: 1. `summary`: a short label. 2. `description`: longer text, which can contain Markdown. 3. `value`: the example body itself. 4. `externalValue`: a URL to the example instead of an inline value. FastAPI exposes it as `openapi_examples`, available on `Path()`, `Query()`, `Header()`, `Cookie()`, `Body()`, `Form()` and `File()`. FastAPI's docstring states the reason to use it: Swagger UI has better support for these OpenAPI-specific examples than for the JSON Schema `examples` list, so this is the way to show a reader several named bodies to choose from, such as a single order and a bulk order. The parameter was added in FastAPI 0.103.0 for exactly that purpose. ## Reading it in openapi.json The quickest way to see the difference is the generated document at `/openapi.json`. For an endpoint with an `Order` body: - `Body(examples=[...])` appears at `requestBody.content["application/json"].schema.examples`, a list next to the `$ref` to the `Order` schema. - `Body(openapi_examples={...})` appears at `requestBody.content["application/json"].examples`, a map keyed by your example names. - `Field(examples=[...])` appears inside `components.schemas.Order.properties`, on the field itself. ## Which one to use - **One representative value per field:** `Field(examples=...)` on the model, so every endpoint that uses the model benefits. - **A whole example body for one endpoint:** `Body(examples=[...])`. - **Several named scenarios a reader should pick from in `/docs`:** `Body(openapi_examples={...})`, with a `summary` on each. ## Pitfalls - **Examples are documentation only.** FastAPI does not validate them against the model. An example with a wrong type or a misspelled key builds into the OpenAPI document without complaint and misleads every client developer who copies it. A test that runs each example through `Order.model_validate` catches that drift. - **Examples do not change parsing.** Declaring an example never makes a field optional or changes how the body is validated. - **`openapi_examples` is a dict, not a list.** Passing a list where FastAPI expects named entries is a common slip. - **Mixing both kinds is allowed.** Field-level JSON Schema examples and endpoint-level `openapi_examples` can coexist; they appear in different places in the document. For an interview, the core is the split: JSON Schema `examples` is a list inside the schema, `openapi_examples` is a named map beside it that Swagger UI renders better, and neither is validated.

  • Does FastAPI check that a request-body example matches the model it documents?
    No. Examples are copied into the OpenAPI document as they are, so a wrong type or a misspelled key builds without complaint. A unit test that validates each declared example with the model's `model_validate` keeps the docs honest.
  • Why does FastAPI deprecate the singular `example` argument on `Body()`?
    Since 0.99.0 FastAPI generates OpenAPI 3.1.0, which is based on JSON Schema 2020-12. That standard has an `examples` list, and the singular `example` keyword is not part of it, so FastAPI keeps `example` working but marks it deprecated in favour of `examples`.

  • FastAPI validates Body() examples against the model at startup
  • openapi_examples takes a plain list of example bodies
  • The singular example argument is the current way to add one example
  • Declaring examples changes how FastAPI parses or validates the body