FastAPI學習-9. Swagger文檔輸出請求示例example


前言

可以在 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 中看起來都是這樣的:

技術細節

關於 example 和 examples...
JSON Schema在最新的一個版本中定義了一個字段 examples ,但是 OpenAPI 基於之前的一個舊版JSON Schema,並沒有 examples.
所以 OpenAPI為了相似的目的定義了自己的 example (使用 example, 而不是 examples), 這也是文檔 UI 所使用的 (使用 Swagger UI).
所以,雖然 example 不是JSON Schema的一部分,但它是OpenAPI的一部分,這將被文檔UI使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM