全局配置
系統(tǒng)路由配置
- OpenAPI Url:默認(rèn)值
/openapi.json
- Swagger UI:默認(rèn)值
/docs
- ReDoc UI:默認(rèn)值
/redoc
Swagger UI 和 ReDoc UI 都是基于 OpenAPI Url 返回的數(shù)據(jù)來渲染頁面的定页,F(xiàn)astAPI 默認(rèn)會開啟這兩種 UI,配置修改方式如下:
from fastapi import FastAPI
app = FastAPI(openapi_url="/api/v2/openapi.json", docs_url="/documentation", redoc_url=None)
Tips:屬性值設(shè)置為
None
時诉儒,表示不開啟
基本信息配置
- 簡單配置方式:
from fastapi import FastAPI
description = """
## Features
- Auto generate openapi json
- Swagger UI & ReDoc UI
"""
app = FastAPI(
title="自定義服務(wù)名",
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:使用
description
和docstring
這兩種方式描述 API 是等價的
狀態(tài)碼及響應(yīng)體配置 - 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
- 參考文檔:Metadata For Tags / Tags
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():
...
棄用標(biāo)識 - Deprecated
@app.delete("/users", deprecated=True)
async def delete_users():
...
其他配置
相關(guān)資料
- Python3 Typing:https://docs.python.org/zh-cn/3/library/typing.html#
- pydantic:https://pydantic-docs.helpmanual.io/