docs에서 Json 스키마에 대해 추가적인 정보를 적어줄 수 도 있다.

JSON 스키마를 정의할 수 있는 방법은 여러가지가 있다.

Pydantic schma_extra

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

    class Config:
        schema_extra = {
            "example": {
                "name": "Foo",
                "description": "A very nice Item",
                "price": 35.4,
                "tax": 3.2,
            }
        }

pydantic 모델에서 Configschema_extra를 정의하면 된다.

Field, Path, Query, Body에도 모두 똑같이 exmple을 추가할 수 있다.

Field 에 변수 추가하기

class Item(BaseModel):
    name: str = Field(..., example="Foo")
    description: Optional[str] = Field(None, example="A very nice Item")
    price: float = Field(..., example=35.4)
    tax: Optional[float] = Field(None, example=3.2)

Body에 변수 추가하기

@app.put("/items/{item_id}")
async def update_item(
    item_id: int,
    item: Item = Body(
        ...,
        example={
            "name": "Foo",
            "description": "A very nice Item",
            "price": 35.4,
            "tax": 3.2,
        },
    ),
):
    results = {"item_id": item_id, "item": item}
    return results

위와 같이 설정이 되면, /docs에 아래와 같이 설정이 된다.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c9195efe-daa5-4944-beb3-9f3f0a91c09d/Untitled.png

Extra Data Types

너무 많기에 직접 보는 걸 추천!

Extra Data Types - FastAPI