FastAP | Swagger文档输出请求示例example

2022-04-22 10:00:00
上海悠悠
转贴:
公众号
2331
摘要:可以在 Swagger文档上看到请求示例example,使用Pydantic schema_extra属性来实现。

前言

可以在 Swagger文档上看到请求示例example,使用Pydantic schema_extra属性来实现。

schema_extra

使用 Config 和 schema_extra 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述:


from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

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,
            }
        }

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {"item_id": item_id, "item": item}
    return results


这些额外的信息将按原样添加到输出的JSON模式中。

Field 的附加参数

在 Field, Path, Query, Body 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 example:

from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

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)

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {"item_id": item_id, "item": item}
    return results


请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。

Body 额外参数

你可以通过传递额外信息给 Field 同样的方式操作Path, Query, Body等。
比如,你可以将请求体的一个 example 传递给 Body:

from typing import Optional

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()

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

@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


文档 UI 中的例子

使用上面的任何方法,它在 /docs 中看起来都是这样的:

fastap-ui-example


技术细节

关于 example 和 examples…
JSON Schema在最新的一个版本中定义了一个字段 examples ,但是 OpenAPI 基于之前的一个旧版JSON Schema,并没有 examples.
所以 OpenAPI为了相似的目的定义了自己的 example (使用 example, 而不是 examples), 这也是文档 UI 所使用的 (使用 Swagger UI).
所以,虽然 example 不是JSON Schema的一部分,但它是OpenAPI的一部分,这将被文档UI使用。

发表评论
评论通过审核后显示。
联系我们
  • 联系人:阿道
  • 联系方式:17762006160
  • 地址:青岛市黄岛区长江西路118号青铁广场18楼