from typing import List
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.post("/files/")
async def create_files(files: List[bytes] = File(...)):
return {"file_sizes": [len(file) for file in files]}
@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
return {"filenames": [file.filename for file in files]}
I am required to get the multiple file upload field as an Optional one The documentation has the above mentioned code but it has no details on how to make the "FileUpload" field as an optional field.
You can use None
instead of ...
(Ellipsis) to make a field Optional
This is an Optional
field.
from typing import Optional
files: Optional[List[bytes]] = File(None)
This a required field.
files: List[bytes] = File(...)
Working example for your case.
from typing import List, Optional
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.post("/files/")
async def create_files(files: Optional[List[bytes]] = File(None)):
return {"file_sizes": [len(file) for file in files]}
@app.post("/uploadfiles/")
async def create_upload_files(files: Optional[List[UploadFile]] = File(None)):
return {"filenames": [file.filename for file in files]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With