Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the file multiple file upload field as an Optional field in FastAPI

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.

like image 451
Nova Sangeeth Avatar asked Mar 02 '23 19:03

Nova Sangeeth


1 Answers

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]}
like image 129
Yagiz Degirmenci Avatar answered May 17 '23 07:05

Yagiz Degirmenci