1

I need to add a description to a FastAPI query parameter, which I pass to the endpoint through a dataclass, in order to display it in OpenAPI/Swagger UI (auto-documentation). How can I do it?

I tried through metadata in fields, but it has no effect (no description for x was added):

enter image description here

To my understanding the dataclass object is used to create a pydantic BaseModel object, which is then used by FastAPI.


Here's my unsuccessful code:

from dataclasses import dataclass, field

from fastapi import FastAPI, Depends

app = FastAPI()


@dataclass
class MyDataclass:
    x: str = field(default=None, metadata={'description': 'descr of x'})


@app.get("/", )
async def root(f: MyDataclass = Depends()):
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}
Chris
  • 18,724
  • 6
  • 46
  • 80
PythonForEver
  • 387
  • 2
  • 15

1 Answers1

1

Instead of the field from dataclass, use Query from pydantic:

from dataclasses import dataclass
from fastapi import FastAPI, Depends, Query

app = FastAPI()


@dataclass
class MyDataclass:
    x: str = Query(default=None, description='descr of x')

enter image description here

PythonForEver
  • 387
  • 2
  • 15