Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing schema name in OpenAPI docs generated by FastAPI

I'm using FastAPI to create backend for my project. I have a method that allows to upload a file. I implemented it as follows:

from fastapi import APIRouter, UploadFile, File

from app.models.schemas.files import FileInResponse

router = APIRouter()


@router.post("", name="files:create-file", response_model=FileInResponse)
async def create(file: UploadFile = File(...)) -> FileInResponse:
    pass

As you can see, I use a dedicated pydantic model for a method result—FileInResponse:

from pathlib import Path

from pydantic import BaseModel


class FileInResponse(BaseModel):
    path: Path

And I follow this naming pattern for models (naming models as <Entity>InCreate, <Entity>InResponse, and so on) throughout the API. However, I couldn't create a pydantic model with a field of the type File, so I had to declare it directly in the route definition (i.e. without a model containing it). As a result, I have this long auto generated name Body_files_create_file_api_files_post in the OpenAPI docs:

Generated OpenAPI docs

Is there a way to change the schema name?

like image 488
goedwig Avatar asked Aug 12 '26 10:08

goedwig


1 Answers

In case someone is interested into renaming auto generated fields from FastAPI in openapi.json file, you should add an operation_id param to your route. This will allow FastAPI to use this id to generate a clearer attribute name for the generated schema.

Before:

@router.post(
    "/{opportunity_id}/files",
    status_code=status.HTTP_201_CREATED,
)
async def attach_opportunity_file(
    db: Database,
    uploaded_file: UploadFile = File(title="File to upload"),
) -> OpportunityFile:
    pass

before-fastapi-swagger

After:

@router.post(
    "/{opportunity_id}/files",
    status_code=status.HTTP_201_CREATED,
    operation_id="attach_opportunity_file", # New operation_id added 
)
async def attach_opportunity_file(
    db: Database,
    uploaded_file: UploadFile = File(title="File to upload"),
) -> OpportunityFile:
    pass

after-fastapi-swagger

like image 81
Samuel RIGAUD Avatar answered Aug 13 '26 23:08

Samuel RIGAUD