How to Handle Multiple File Upload in FastAPI Correctly
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.
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)}
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.
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
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.