簡介
FastAPI是流行的Python web框架,適用于開發(fā)高吞吐量API和微服務(wù)(直接支持異步編程)
FastAPI的優(yōu)勢之一:通過提供高級(jí)抽象和自動(dòng)數(shù)據(jù)模型轉(zhuǎn)換,簡化請(qǐng)求數(shù)據(jù)的處理(用戶不需要手動(dòng)處理原始請(qǐng)求數(shù)據(jù)),并能根據(jù)路由和 Pydantic 模型自動(dòng)生成 OpenAPI 接口文檔。
- Swagger UI
- ReDoc
demo
import uuid
import uvicorn
from typing import Any, Union, Optional
from typing_extensions import Literal
from fastapi import Body, FastAPI
from pydantic import (
BaseModel,
Field,
UUID4
)
app = FastAPI()
class UserIn(BaseModel):
channel: Literal[0, 1] = Field(0, title="渠道")
username: str = Field(..., title="用戶名")
password: str = Field(..., title="用戶密碼", description="長度6-8位")
email: str = Field(..., title="用戶郵箱地址")
full_name: str = Field(None, title="用戶全名")
request_id: Optional[UUID4]
class UserOut(BaseModel):
username: str = Field(..., title="用戶名")
email: str = Field(..., title="用戶郵箱地址")
full_name: str = Field(None, title="用戶全名")
request_id: Optional[UUID4]
# FastAPI will take care of filtering out all the data that is not declared in the output model (using Pydantic).
# 因此,F(xiàn)astAPI將負(fù)責(zé)過濾掉輸出模型中未聲明的所有數(shù)據(jù)(使用Pydantic)。
@app.post("/user/", response_model=UserOut)
async def create_user(
user: UserIn = Body(
examples={
"example1": {
"summary": "A short summary or description of the example",
"value": {
# example data here
"channel": 0,
"username": "Foo",
"password": "33759",
"email": "chencare@163.com",
"full_name": "xiaotao"
}
}
})
) -> UserOut:
user.request_id = uuid.uuid4()
print(user.request_id)
return user
if __name__ == '__main__':
uvicorn.run(app=app, access_log=True, port=9988)
運(yùn)行后,會(huì)提示Uvicorn running on http://127.0.0.1:9988 (Press CTRL+C to quit)
在瀏覽器輸入http://127.0.0.1:9988/redoc
( ReDoc),http://127.0.0.1:9988/docs
(Swagger UI )即可查看
ReDoc 頁面如下:
ReDoc vs. Swagger UI文章來源:http://www.zghlxwxcb.cn/news/detail-765427.html
ReDoc更美觀,Swagger UI更注重交互(用戶直接從界面中發(fā)送請(qǐng)求,查看響應(yīng),這對(duì)于測試和調(diào)試 API 非常有用。)文章來源地址http://www.zghlxwxcb.cn/news/detail-765427.html
到了這里,關(guān)于【web】Fastapi自動(dòng)生成接口文檔(Swagger、ReDoc )的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!