Reputation: 41
I am trying to make UploadFile
optional in FastAPI, in the process, I am able to make a single file optional, but got an error if I convert it to multiple files.
# Making optional for single uploadfile
@app.post("/optional-file")
async def optionalFile(file: Optional[UploadFile] = File(None)):
if not file:
print("no file")
return "no file"
print(file.filename)
return {"name": file.filename}
# Making optional for multiple uploadfile
@app.post("/optional-files")
async def optionalFiles(files: Optional[List[UploadFile]] = File(None)):
if not files:
print("no files")
return "no files"
print(file[0].filename)
return {"name": file[0].filename}
and I am getting this error in return.
{"detail":[{"loc":["body","files",0],"msg":"Expected UploadFile, received: <class 'str'>","type":"value_error"}]}
Thanks in advance for any sort of help provided.
Upvotes: 4
Views: 1219
Reputation: 131
I solved it with:
def get_files(files_list: List[Union[UploadFile, str]] = File(None)):
if isinstance(files_list, str):
files_list = []
I send '', if i have no files to send.
Upvotes: 2