A FastAPI bulk CSV import endpoint takes an UploadFile; what limits the upload's size by default, and how would you cap it?
answer
- the framework itself sets no cap
- counts and text parts, not files
- 400 from the parser, not 413
- stop it before the body is spooled
basics
~20 sNothing caps a file's size by default: Starlette's parser limits only counts (1000 files, 1000 fields) and non-file parts (1 MB), answering 400. Cap uploads at the reverse proxy and with Starlette's RequestBodyLimitMiddleware, which answers 413.
solid answer
~40 sFastAPI sets no size limit. Before the endpoint runs it calls Starlette's `request.form()` with defaults, which spools every file part into a temporary file and only enforces `max_files=1000`, `max_fields=1000` and `max_part_size` of 1 MB for **non-file** parts, raising a 400 with a message like `Too many files. Maximum number of files is 1000.` A file part has no cap, so one client can fill the temp directory, and checking `file.size` in the endpoint is too late. I cap the body at the reverse proxy, and in the app with Starlette's `RequestBodyLimitMiddleware` (Starlette 1.6+) via `app.add_middleware(..., max_body_size=...)`: it counts body bytes and answers 413. `FastAPI(max_body_size=...)` is silently ignored. For tighter counts I can call `request.form(max_files=..., max_part_size=...)` myself, knowing that still does not limit files.
code
python · 13 linesfrom fastapi import FastAPI, UploadFile
from starlette.middleware.body_limit import RequestBodyLimitMiddleware
app = FastAPI()
# Starlette 1.6+: refuses an oversized Content-Length before reading and
# counts the streamed bytes, answering 413 Content Too Large.
app.add_middleware(RequestBodyLimitMiddleware, max_body_size=5 * 1024 * 1024)
# FastAPI(max_body_size=...) would only land in app.extra and limit nothing.
@app.post("/imports/orders")
async def import_orders(file: UploadFile):
return {"filename": file.filename, "size": file.size}go deeper
Recall that FastAPI does not limit upload size itself, and that limits belong in front of the endpoint.
Explain Starlette's defaults, max_files, max_fields and the 1 MB max_part_size for non-file parts, and that breaking them returns 400.
Show where the upload is stored before the endpoint runs, why an endpoint check is too late, and how a proxy limit or Starlette's RequestBodyLimitMiddleware stops it.
Decide the per-endpoint maximums, keep proxy and app limits consistent, size temp storage for concurrent uploads, and route very large files to object storage.
The short answer surprises many teams: **FastAPI itself does not cap an upload's size**. The limits that apply by default come from Starlette's form parser, and they are counts and per-field sizes, not a size limit on files. A total body cap exists in Starlette, but only once you add it. ## When the upload is actually received A path operation with an `UploadFile` or `File()` parameter does not see the request until the body has been parsed: 1. FastAPI calls Starlette's `request.form()` with its default arguments. 2. Starlette streams the body through python-multipart. Each file part is written into a `SpooledTemporaryFile` that stays in memory up to 1 MB and then rolls to a temporary file on disk. 3. Only when the whole body has been read does FastAPI validate the parameters and call your endpoint. So by the time your code can look at `file.size`, the bytes have already been received and written to disk. A check there is a business rule, not a protection. The rolled-over files are created by Python's `tempfile` module in the directory it picks, which honours the `TMPDIR` environment variable, and their space is released when FastAPI closes them after the request. In a container that directory often sits on a small writable layer, which is why disk, not memory, is usually the first thing an unbounded upload exhausts. ## The limits Starlette applies by default | Limit | Default | Applies to | |---|---|---| | `max_files` | 1000 | file parts in one multipart body | | `max_fields` | 1000 | non-file fields, multipart or URL-encoded | | `max_part_size` | 1 MB | each **non-file** part, and each URL-encoded field | | size of a file part | none | file parts are only spooled | | total body size | none by default | `RequestBodyLimitMiddleware`, once you add it | When a limit is exceeded inside an application, Starlette raises an `HTTPException` with status **400** and a detail such as `Too many files. Maximum number of files is 1000.` or `Part exceeded maximum size of 1024KB.` It is a 400, not a 413, and FastAPI exposes no parameter on `Form()`, `File()` or the route to change these numbers. Uvicorn does not cap the request body by default either. A client can therefore send one multi-gigabyte file part, and the worker will write all of it to the temporary directory before the endpoint runs; several such clients at once can fill a container's disk. ## Where to put a real cap Work from the outside in: 1. **The reverse proxy or load balancer** in front of the app usually has a request-body size limit. It is the cheapest place, because an oversized body never reaches Python. 2. **Starlette's `RequestBodyLimitMiddleware`** (`starlette.middleware.body_limit`, since Starlette 1.6), added with `app.add_middleware(RequestBodyLimitMiddleware, max_body_size=...)` as in the example. It refuses a declared `Content-Length` over the limit before reading, and it also counts the bytes of each `http.request` message, so a chunked request or an understated header still stops with a 413 `Content Too Large`. A `Content-Length` check alone would not be enough. Starlette's own app, `Router`, `Mount` and `Route` take `max_body_size` as well, but FastAPI 0.143 does not pass it on: `FastAPI(max_body_size=...)` only lands in `app.extra` and limits nothing, and `APIRouter` rejects the argument. 3. **Tighter parser counts** for one endpoint: take a `Request` parameter and call `await request.form(max_files=1, max_fields=5, max_part_size=64 * 1024)` yourself, ideally as `async with request.form(...) as form:` so the files are closed. This limits how many parts arrive and how large text fields are, but `max_part_size` still does not bound a file part. 4. **Inside the endpoint**, check `file.size` or count rows for rules such as "at most 50,000 orders per import", and answer with a clear error; this runs after the upload is stored. ## Choosing the numbers - Base the cap on the largest legitimate file plus multipart overhead, per endpoint if one route takes much larger files than the rest. - Remember that the disk cost is concurrent uploads times the cap, and size the temporary directory or volume for it. - Keep the proxy limit and the in-app limit consistent, so clients see one documented maximum and a 413 rather than a reset connection or a 400 from the parser. - Very large imports are often better sent straight to object storage and processed afterwards, which keeps them out of the API process entirely. A good interview answer names all three layers: FastAPI none, Starlette counts and text-part sizes with a 400, and a size cap you add yourself, at the proxy and with Starlette's `RequestBodyLimitMiddleware`.
- Why is rejecting an oversized upload by checking UploadFile.size inside a FastAPI endpoint not a protection?FastAPI parses the whole multipart body before calling the endpoint, so the file has already been received and spooled to disk when `size` is read. The check can still enforce a business rule and return a clear error, but bandwidth, time and disk have been spent. Protection has to sit before parsing, at the proxy or in body-counting middleware such as Starlette's `RequestBodyLimitMiddleware`.
- Can a FastAPI middleware cap upload size by reading the Content-Length header alone?Only partly. It can reject a declared oversized body early, but a request sent with chunked transfer encoding carries no `Content-Length`. A robust middleware also counts the bytes it actually passes on, stopping with a 413 when the total passes the limit; Starlette's `RequestBodyLimitMiddleware` does both.
- FastAPI rejects uploads above a built-in default size limit.
- Starlette's max_part_size of 1 MB also limits each uploaded file.
- A form that exceeds Starlette's limits is answered with 413.
- Checking file.size in the endpoint stops the upload before it is stored.
- A Content-Length check alone is enough to bound every request body.
- Passing max_body_size to FastAPI() caps the request body.
Assumes FastAPI 0.143 on Starlette 1.7; RequestBodyLimitMiddleware and max_body_size arrived in Starlette 1.6.0, so material written for older Starlette rightly says nothing in the stack can cap the body.