【web】Fastapi主动天生接口文档(Swagger、ReDoc )
简介FastAPI是盛行的Python web框架,适用于开发高吞吐量API和微服务(直接支持异步编程)
FastAPI的上风之一:通过提供高级抽象和主动数据模型转换,简化哀求数据的处置处罚(用户不需要手动处置处罚原始哀求数据),并能根据路由和 Pydantic 模型主动天生 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 = 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
class UserOut(BaseModel):
username: str = Field(..., title="用户名")
email: str = Field(..., title="用户邮箱地址")
full_name: str = Field(None, title="用户全名")
request_id: Optional
# FastAPI will take care of filtering out all the data that is not declared in the output model (using Pydantic).
# 因此,FastAPI将负责过滤掉输出模型中未声明的所有数据(使用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)
运行后,会提示Uvicorn running on http://127.0.0.1:9988 (Press CTRL+C to quit)
https://i-blog.csdnimg.cn/blog_migrate/9d24fe699eb069e6865f5e7481fe51ae.png
在欣赏器输入http://127.0.0.1:9988/redoc( ReDoc),http://127.0.0.1:9988/docs(Swagger UI )即可查察
ReDoc 页面如下:
https://i-blog.csdnimg.cn/blog_migrate/9170c5bacfa9fb7e8672fdc7447ca4d1.png
ReDoc vs. Swagger UI
ReDoc更美观,Swagger UI更注意交互(用户直接从界面中发送哀求,查察响应,这对于测试和调试 API 非常有用。)
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]