fastapi-utils icon indicating copy to clipboard operation
fastapi-utils copied to clipboard

[FEATURE] Update schema name for 'UploadFile' routes.

Open synchronizing opened this issue 3 years ago • 0 comments

This is a problem that arose on FastAPI#1442. In essence, when creating an upload endpoint like the one detailed here, FastAPI automatically generates the schema names for the UploadFile (or bytes) with no customization setting.

Screen Shot 2021-03-02 at 1 01 02 AM

This is modifiable via a simple function that updates the model class name:

def update_upload_schema_name(app: FastAPI, function: Callable, name: str) -> None:
    """
    Updates the Pydantic schema name for a FastAPI function that takes
    in a fastapi.UploadFile = File(...) or bytes = File(...).
    """
    for route in app.routes:
        if route.endpoint == function:
            route.body_field.type_.__name__ = name
            break

The example linked above in the FastAPI endpoint therefore becomes:

from fastapi import FastAPI, File, UploadFile
from typing import Callable

app = FastAPI()

@app.post("/files/")
async def create_file(file: bytes = File(...)):
    return {"file_size": len(file)}

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

def update_upload_schema_name(app: FastAPI, function: Callable, name: str) -> None:
    """
    Updates the Pydantic schema name for a FastAPI function that takes
    in a fastapi.UploadFile = File(...) or bytes = File(...).
    """
    for route in app.routes:
        if route.endpoint == function:
            route.body_field.type_.__name__ = name
            break

update_upload_schema_name(app, create_file, "CreateFileSchema")
update_upload_schema_name(app, create_upload_file, "CreateUploadSchema")

And outputs:

Screen Shot 2021-03-02 at 1 02 20 AM

I was wondering if the devs of this repo would find this function useful. Since I have not read through the code of this repo, I'm unsure if there are better ways to add this feature. If someone could guide me to where this could possibly be added, I would be happy to submit PR. 🤙

synchronizing avatar Mar 02 '21 06:03 synchronizing