How to use openapi_examples with Pydantic? #10233
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI
from fastapi.openapi.models import Example
from pydantic import BaseModel, ConfigDict, Field
app = FastAPI()
class CreateRequest1(BaseModel):
name: str = Field(..., description="Name of the created item")
value: str = Field(..., description="Value of the created item")
model_config = ConfigDict(json_schema_extra={"examples": [{"name": "Item1", "value": "Value1"}]})
class CreateRequest2(BaseModel):
name: str = Field(..., description="Name of the created item")
value: str = Field(..., description="Value of the created item")
model_config = ConfigDict(
json_schema_extra={
"openapi_examples": {
"abc": Example(summary="test", description="test", value={"name": "Item1", "value": "Value1"})
}
}
)
@app.post("/1")
def create_item1(body: CreateRequest1):
return CreateRequest1.name
@app.post("/2")
def create_item2(body: CreateRequest2):
return CreateRequest2.nameDescriptionHow can I use
I also couldn't find any example in the documentation. Operating SystemLinux Operating System DetailsNo response FastAPI Version0.103.1 Pydantic Version2.3.0 Python Version3.11.5 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
@tiangolo any suggestions here? |
Beta Was this translation helpful? Give feedback.
-
|
You can specify examples for request body from typing import Annotated
from fastapi import Body, FastAPI
from fastapi.openapi.models import Example
from pydantic import BaseModel, Field
app = FastAPI()
class CreateRequest2(BaseModel):
name: str = Field(..., description="Name of the created item")
value: str = Field(..., description="Value of the created item")
@app.post("/2")
def create_item2(
body: Annotated[
CreateRequest2,
Body(
openapi_examples={
"abc": Example(
summary="test",
description="test",
value={"name": "Item1", "value": "Value1"},
)
}
),
],
):
return CreateRequest2.nameBut, there is a tricky thing here: it will only work if you have only one |
Beta Was this translation helpful? Give feedback.
openapi_examplesis a parameter ofBody, it's not a part of JSON schema (json_schema_extrais supposed to be used to modify the JSON schema).You can specify examples for request body