Use Union type annotation
from fastapi import FastAPI, UploadFile, Form, File
from typing import Union
app = FastAPI()
@app.post(path="/")
async def predict(
static: str = Form(...),
file: Union[UploadFile, str] = File(...)
):
return {
"received_static": static,
"received_file": file if isinstance(file, str) else file.filename
}
AFAIK, OpenAPI schema doesn't support this config since it doesn't support multiple types. So, better to define multiple parameters to handle things differently. Also, IMHO, it is the better way
from fastapi import FastAPI, UploadFile, Form, File
app = FastAPI()
@app.post(path="/")
async def predict(
static: str = Form(...),
file: UploadFile = File(None), # making optional
file_str: str = Form(None) # making optional
):
return {
"received_static": static,
"received_file": file.filename if file else None,
"received_file_str": file_str if file_str else ''
}