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

简介

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

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

  • Swagger UI
  • ReDoc

demo

python 复制代码
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).
# 因此,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)

在浏览器输入http://127.0.0.1:9988/redoc( ReDoc),http://127.0.0.1:9988/docs(Swagger UI )即可查看

ReDoc 页面如下:

ReDoc vs. Swagger UI

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

相关推荐
十一.3667 小时前
37-38 for循环
前端·javascript·html
波诺波7 小时前
环境管理器
linux·前端·python
诸葛思颖7 小时前
把本地 Python 项目用 Git 进行版本控制并推送到 GitHub
git·python·github
测试老哥7 小时前
自动化测试用例的编写和管理
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
San30.8 小时前
深入理解浏览器渲染流程:从HTML/CSS到像素的奇妙旅程
前端·css·html
IT_陈寒8 小时前
5个Python 3.12新特性让你的代码效率提升50%,第3个太实用了!
前端·人工智能·后端
周杰伦_Jay8 小时前
【Python Web开源框架】Django/Flask/FastAPI/Tornado/Pyramid
前端·python·开源
周杰伦_Jay8 小时前
【Python后端API开发对比】FastAPI、主流框架Flask、Django REST Framework(DRF)及高性能框架Tornado
数据结构·人工智能·python·django·flask·fastapi·tornado
chenchihwen8 小时前
AI代码开发宝库系列:PDF文档解析MinerU
人工智能·python·pdf·dashscope
艾小码8 小时前
为什么你的JavaScript代码总是出bug?这5个隐藏陷阱太坑了!
前端·javascript