4

例如假设我们有两个端点:

class FooRequest(BaseModel):
    data: str


@router.post("/foo/", response_model=FooRequest)
async def foo_view(data: FooRequest) -> FooRequest:
    ...


@router.get("/bar/", response_model=FooRequest)
async def bar_view(data: str = Query(..., description="Data param")) -> FooRequest:
    ...

在 swagger UI/bar/端点将有正确记录的查询参数,/foo/并将有一些没有任何描述的帖子正文的抽象示例。

那么我如何记录后身体模型呢?

4

1 回答 1

4

Config您可以使用和声明 Pydantic 模型的示例schema_extra

class FooRequest(BaseModel):
    data: str

    class Config:
        schema_extra = {
            "FooRequest": {
                "name": "Foo Request",
                "description": "Data param",
            }
        }

您还可Field以为您的 JSON Schema 声明额外信息。

from pydantic import Field

...

class FooRequest(BaseModel):
    data: str = Field(..., example="Data param for Foo Request")
    description: Optional[str] = Field(None, example="Description for Foo")

与将额外信息传递给 的方式相同,您也可以对, ,等Field执行相同的操作。PathQueryBody

例如,您可以将正文请求的示例传递给Body

from fastapi import Body

...

class FooRequest(BaseModel):
    data: str


@router.post("/foo/", response_model=FooRequest)
async def foo_view(data: FooRequest = Body(
            ...,
            example={
                "name": "Foo Request",
                "description": "data param",
            },
        ),
    ) -> FooRequest:
    
于 2020-07-16T11:08:21.533 回答