How to group FastAPI endpoints in Swagger UI? [closed]
Asked Answered
D

1

18

I started programming using FastAPI framework and it comes with a builtin Swagger interface to handle requests and responses. I have completed nearly 20 APIs and its hard to manage and recognise APIs on Swagger interface. Someone told me to add sections in Swagger interface to distinguish APIs, but I couldn't find any examples and I need help.

Divalent answered 6/9, 2020 at 8:56 Comment(0)
G
46

You can add tags to your path parameter, for example.

If you have something like this, using tags is extremely helpful.

@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

You will get this, also if you want to add description and you don't want to keep repating yourself (For example adding same description in all parameters)

You can use openapi_tags (I prefer this)

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=["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

This will give the same look without repetition

enter image description here

Girvin answered 6/9, 2020 at 9:44 Comment(2)
Also worth noting that tags can be put directly on APIRouter objects tooDanger
Do we also have such metadata for fields description ? ( there are some text inputs that I need in almost every endpoint )Omeara

© 2022 - 2024 — McMap. All rights reserved.