【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": "[email protected]",
                        "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 非常有用。)

相关推荐
心扬2 分钟前
python网络编程
开发语言·网络·python·tcp/ip
忧陌6065 分钟前
DAY 44 预训练模型
python
BillKu7 分钟前
scss(sass)中 & 的使用说明
前端·sass·scss
疯狂的沙粒11 分钟前
uni-app 项目支持 vue 3.0 详解及版本升级方案?
前端·vue.js·uni-app
Jiaberrr21 分钟前
uniapp Vue2 获取电量的独家方法:绕过官方插件限制
前端·javascript·uni-app·plus·电量
点云SLAM22 分钟前
PyTorch 中contiguous函数使用详解和代码演示
人工智能·pytorch·python·3d深度学习·contiguous函数·张量内存布局优化·张量操作
尘浮72835 分钟前
60天python训练计划----day45
开发语言·python
哆啦A梦的口袋呀1 小时前
基于Python学习《Head First设计模式》第六章 命令模式
python·学习·设计模式
努力搬砖的咸鱼1 小时前
从零开始搭建 Pytest 测试框架(Python 3.8 + PyCharm 版)
python·pycharm·pytest
Calvex1 小时前
PyCharm集成Conda环境
python·pycharm·conda