如何在Swagger UI中对FastAPI端点进行分组?

问题描述

我开始使用fastApi框架进行编程,它带有内置的swagger接口来处理请求和响应。 我已经完成了将近20个api,很难在swagger界面上管理和识别api。 有人告诉我在swagger界面中添加一些部分来区分api,但我在Google上找不到任何示例,因此需要你们的帮助。

预先感谢...

解决方法

例如,您可以在路径参数中添加标记

如果您有类似的事情,使用标签非常有帮助。

@app.delete("/items",tags=["Delete Methods"])
@app.put("/items",tags=["Put Methods"])
@app.post("/items",tags=["Post Methods"])
@app.get("/items",tags=["Get Methods"])
async def handle_items():
    return


@app.get("/something",tags=["Get Methods"])
async def something():
    return

enter image description here

如果您想添加说明并且不想一直重复自己(例如,在所有参数中添加相同的说明),也会得到此提示

您可以使用 openapi_tags (我更喜欢)

from fastapi import FastAPI

tags_metadata = [
    {"name": "Get Methods","description": "One other way around"},{"name": "Post Methods","description": "Keep doing this"},{"name": "Delete Methods","description": "KILL 'EM ALL"},{"name": "Put Methods","description": "Boring"},]

app = FastAPI(openapi_tags=tags_metadata)


@app.delete("/items",tags=["Get Methods"])
async def handle_items():
    return

这将赋予相同外观,而无需重复

enter image description here