Python / FastAPI Basics Interview Questions
How do you handle form data and file uploads in FastAPI?
FastAPI handles HTML form data with Form() and file uploads with File() and UploadFile. Note: you need to pip install python-multipart for form/file support.
from fastapi import FastAPI, Form, File, UploadFile from typing import Annotated app = FastAPI() # Form data (application/x-www-form-urlencoded) @app.post("/login") def login( username: Annotated[str, Form()], password: Annotated[str, Form()], ): return {"username": username} # Single file upload @app.post("/upload") async def upload_file(file: UploadFile): contents = await file.read() # bytes return { "filename": file.filename, "content_type": file.content_type, "size": len(contents), } # Multiple files @app.post("/upload-multiple") async def upload_files(files: list[UploadFile]): return [{"filename": f.filename} for f in files] # Mix form fields + file @app.post("/profile") async def update_profile( username: Annotated[str, Form()], avatar: UploadFile | None = None, ): result = {"username": username} if avatar: content = await avatar.read() # Save to disk / cloud storage result["avatar_size"] = len(content) return result # Validate file type and size @app.post("/images") async def upload_image(file: UploadFile): if file.content_type not in ["image/jpeg", "image/png"]: from fastapi import HTTPException raise HTTPException(400, "Only JPEG/PNG allowed") content = await file.read() if len(content) > 5 * 1024 * 1024: # 5 MB limit raise HTTPException(400, "File too large") return {"filename": file.filename}
More Related questions...