Python File Upload with FastAPI

Handle file uploads in FastAPI using UploadFile with async streaming, file size validation, MIME type checking, background task processing, and multiple.

PythonFastapiFile Upload

Code

snippet
from fastapi import FastAPI, UploadFile, File, BackgroundTasks
import aiofiles
import os

app = FastAPI()
MAX_SIZE = 10 * 1024 * 1024

@app.post('/upload')
async def upload(file: UploadFile = File(...), bg: BackgroundTasks = BackgroundTasks()):
    if file.content_type not in ['image/png', 'image/jpeg', 'application/pdf']:
        return {'error': 'Unsupported type'}
    content = await file.read()
    if len(content) > MAX_SIZE:
        return {'error': 'File too large'}
    async with aiofiles.open(f'uploads/{file.filename}', 'wb') as f:
        await f.write(content)
    return {'filename': file.filename, 'size': len(content)}

Inside the snippet

Python File Upload with FastAPI comes down to the function upload.

Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. FastAPI, UploadFile, File, BackgroundTasks are the only symbols borrowed from fastapi — the coupling is explicit and narrow.

It builds and returns a fresh value rather than reusing its inputs.

Watch out for

  • Plan for an install step: fastapi and aiofiles are a real dependency, resolved by the package manager.

Using it

The primary signature is def upload(file: UploadFile = File(...)

upload is what another module would consume; nothing else here is load-bearing for callers.

Key statements

async with aiofiles.open(f'uploads/{file.filename}', 'wb') as f:
    await f.write(content)
return {'filename': file.filename, 'size': len(content)}
return {'error': 'Unsupported type'}

FAQ

Does `upload` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Are there third-party dependencies?
`fastapi` and `aiofiles` — install them with the package manager before running.