0
0
FastapiDebug / FixBeginner · 4 min read

How to Handle Multiple File Upload in FastAPI Correctly

To handle multiple file uploads in FastAPI, use List[UploadFile] as the parameter type with File(...). This allows FastAPI to receive and process multiple files sent in one request correctly.
🔍

Why This Happens

When trying to upload multiple files, a common mistake is to use a single UploadFile parameter instead of a list. FastAPI then expects only one file, causing errors or ignoring extra files.

python
from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    content = await file.read()
    return {"filename": file.filename, "size": len(content)}
Output
Only one file is accepted; sending multiple files causes an error or only the first file is processed.
🔧

The Fix

Change the parameter type to List[UploadFile] and import List from typing. This tells FastAPI to expect multiple files and handle them as a list.

python
from fastapi import FastAPI, UploadFile, File
from typing import List

app = FastAPI()

@app.post("/upload")
async def upload_files(files: List[UploadFile] = File(...)):
    results = []
    for file in files:
        content = await file.read()
        results.append({"filename": file.filename, "size": len(content)})
    return results
Output
[{"filename": "file1.txt", "size": 123}, {"filename": "file2.jpg", "size": 4567}]
🛡️

Prevention

Always use List[UploadFile] when expecting multiple files in FastAPI. Test your endpoints with tools like Postman or curl to confirm multiple files upload correctly. Follow FastAPI's documentation examples to avoid parameter type mistakes.

⚠️

Related Errors

Errors like 422 Unprocessable Entity often happen if the parameter type does not match the request data. Also, forgetting to use File(...) can cause FastAPI to not recognize the file input properly.

Key Takeaways

Use List[UploadFile] with File(...) to accept multiple files in FastAPI.
Import List from typing to define multiple file parameters correctly.
Test file uploads with API tools to ensure correct request format.
Always match parameter types with expected request data to avoid errors.