Reputation: 2129
I have a function like this,
async def predict(static: str = Form(...), file: UploadFile = File(...)):
return something
I have two parameters here, static and file and static is a string, file is buffer of uploaded file.
Now, is there a way to assign multiple types to one parameter, i.e., I want to make file
parameter take either upload file or just string
Upvotes: 2
Views: 3841
Reputation: 88499
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 ''
}
Upvotes: 3