How can I create Swagger docs for dynamic FastAPI endpoints?

Question:

I have a list of endpoints like below.

endpoints ["/endpoint1", "/endpoint2", "/endpoint3"]

I would like to create dynamic endpoints in my app and create swagger API docs for all the endpoints, how can I do this.

@app.route(<endpoint>):
  def process():
Asked By: Pyd

||

Answers:

Use Enum–(FastAPI doc) classes

from enum import Enum
from fastapi import FastAPI


class ModelName(str, Enum):
    endpoint1 = "endpoint1"
    endpoint2 = "endpoint2"
    endpoint3 = "endpoint3"


app = FastAPI()


@app.get("/model/{model_name}")
async def process(model_name: ModelName):
    return {"model_name": model_name, "message": "Some message"}

and thus you will get the result as follows,

enter image description here

Answered By: JPG
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.