Python / FastAPI 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}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
