fastapi-utils
fastapi-utils copied to clipboard
[FEATURE] Update schema name for 'UploadFile' routes.
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.
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:
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. 🤙