0


【web】Fastapi自动生成接口文档(Swagger、ReDoc )

简介

FastAPI是流行的Python web框架,适用于开发高吞吐量API和微服务(直接支持异步编程)

FastAPI的优势之一:通过提供高级抽象和自动数据模型转换,简化请求数据的处理(用户不需要手动处理原始请求数据),并能根据路由和 Pydantic 模型自动生成 OpenAPI 接口文档。

  • Swagger UI
  • ReDoc

demo

  1. import uuid
  2. import uvicorn
  3. from typing import Any, Union, Optional
  4. from typing_extensions import Literal
  5. from fastapi import Body, FastAPI
  6. from pydantic import(
  7. BaseModel,
  8. Field,
  9. UUID4
  10. )
  11. app = FastAPI()classUserIn(BaseModel):
  12. channel: Literal[0,1]= Field(0, title="渠道")
  13. username:str= Field(..., title="用户名")
  14. password:str= Field(..., title="用户密码", description="长度6-8位")
  15. email:str= Field(..., title="用户邮箱地址")
  16. full_name:str= Field(None, title="用户全名")
  17. request_id: Optional[UUID4]classUserOut(BaseModel):
  18. username:str= Field(..., title="用户名")
  19. email:str= Field(..., title="用户邮箱地址")
  20. full_name:str= Field(None, title="用户全名")
  21. request_id: Optional[UUID4]# 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)asyncdefcreate_user(
  22. user: UserIn = Body(
  23. 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:
  24. user.request_id = uuid.uuid4()print(user.request_id)return user
  25. if __name__ =='__main__':
  26. uvicorn.run(app=app, access_log=True, port=9988)

运行后,会提示

  1. Uvicorn running on http://127.0.0.1:9988 (Press CTRL+C to quit)

在这里插入图片描述

在浏览器输入

  1. http://127.0.0.1:9988/redoc

( ReDoc),

  1. http://127.0.0.1:9988/docs

(Swagger UI )即可查看

ReDoc 页面如下:
在这里插入图片描述

ReDoc vs. Swagger UI

ReDoc更美观,Swagger UI更注重交互(用户直接从界面中发送请求,查看响应,这对于测试和调试 API 非常有用。)

标签: 前端 fastapi python

本文转载自: https://blog.csdn.net/qq_39317214/article/details/134605616
版权归原作者 larrino 所有, 如有侵权,请联系我们删除。

“【web】Fastapi自动生成接口文档(Swagger、ReDoc )”的评论:

还没有评论