FastAPI - OpenAPI 入门指南

全局配置

系统路由配置

  • OpenAPI Url:默认值 /openapi.json
  • Swagger UI:默认值 /docs
  • ReDoc UI:默认值 /redoc

Swagger UI 和 ReDoc UI 都是基于 OpenAPI Url 返回的数据来渲染页面的,FastAPI 默认会开启这两种 UI,配置修改方式如下:

from fastapi import FastAPI

app = FastAPI(openapi_url="/api/v2/openapi.json", docs_url="/documentation", redoc_url=None)

Tips:属性值设置为 None 时,表示不开启

基本信息配置

  • 简单配置方式:
from fastapi import FastAPI

description = """
## Features
- Auto generate openapi json
- Swagger UI & ReDoc UI
"""

app = FastAPI(
    title="自定义服务名",
    description=description,
    version="2.2.1",
    terms_of_service="http://example.com/terms/",
    contact={
        "name": "Anoyi",
        "url": "https://anoyi.com",
        "email": "anoyi@qq.com",
    },
    license_info={
        "name": "Apache 2.0",
        "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
    },
)

if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=8080, access_log=False, debug=True)
  • 高级配置方式:
from fastapi import FastAPI

app = FastAPI()

description = """
## Features
- Auto generate openapi json
- Swagger UI & ReDoc UI
"""

app.openapi()["info"] = {
    "title": "Custom Title",
    "version": "2.2.0",
    "description": description,
    "contact": {
        "name": "Anoyi",
        "url": "https://anoyi.com",
        "email": "anoyi@qq.com",
    },
    "license": {
        "name": "Apache 2.0",
        "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
    },
    "x-logo": {
        "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png"
    }
}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8080, access_log=False, debug=True)

Tips:description 支持 Markdown 格式

API 配置

基本配置

from typing import Generic, TypeVar, Optional

from fastapi import FastAPI, Cookie, Header
from pydantic import BaseModel
from pydantic.generics import GenericModel

T = TypeVar('T')


class WebResponse(GenericModel, Generic[T]):
    code: int
    message: Optional[str]
    data: Optional[T]


class Item(BaseModel):
    item_id: str
    item_name: str
    item_size: Optional[int]


@app.get("/item/{item_id}", name='Get Item By Id', description='Description Of Get A Item', response_model=WebResponse[str])
async def read_item(item_id: str, q: str, user_agent: Optional[str] = Header(None), session: Optional[str] = Cookie(None)):
    print(f'item_id: {item_id}')
    print(f'query -> q: {q}')
    print(f'header -> User-Agent: {user_agent}')
    print(f'cookie -> session: {session}')
    return WebResponse(code=0, data=item_id).dict()


@app.post("/item", name='Add Item', description='Description Of Add A Item', response_model=WebResponse[Item], response_description="The created item")
async def create_item(body: Item):
    print(f'body: {body.dict()}')
    return WebResponse[Item](code=0, data=body).dict()


@app.put("/item", summary="Update Item", response_model=WebResponse[bool], tags=["Items"])
async def create_item(body: Item):
    """
    Update A Item

    - **item_id**: each item must have a id
    - **item_name**: each item must have a name
    - **item_size**: set the item's size
    """
    print(f"body: {body.dict()}")
    return WebResponse[Item](code=0, data=True).dict()

Tips:使用 descriptiondocstring 这两种方式描述 API 是等价的

状态码及响应体配置 - Status Code & Response Example

from starlette.responses import FileResponse

responses = {
    200: {"content": {"image/png": {}}},
    403: {
        "description": "Not enough privileges",
        "content": {
            "application/json": {
                "example": {"id": "100001", "reason": "Not enough privileges"}
            }
        },
    },
    404: {"description": "Image not found"},
}


@app.get("/image/{image_id}", name="Read Image", response_class=FileResponse, responses=responses)
async def read_item(image_id: str):
    return FileResponse(f"{image_id}.png", media_type="image/png")

分组配置 - Tags & Group

tags_metadata = [
    {
        "name": "Items",
        "description": "Manage items. So _fancy_ they have their own docs.",
        "externalDocs": {
            "description": "Items external docs",
            "url": "https://fastapi.tiangolo.com/",
        },
    },
    {
        "name": "Media",
        "description": "Operations with Media. The **video** logic is also here.",
    },
]

app = FastAPI(openapi_tags=tags_metadata)


@app.post("/item", tags=["Items"])
async def create_item(item: Item):
    ...


@app.get("/item", tags=["Items"])
async def read_items():
    ...


@app.get("/media", tags=["Media"])
async def read_media():
    ...

弃用标识 - Deprecated

@app.delete("/users", deprecated=True)
async def delete_users():
    ...

其他配置

相关资料

推荐阅读更多精彩内容