
A FastAPI file upload endpoint needs to decide what it will accept, how much data it will read, and where accepted files will live. Receiving an UploadFile is one part of that job. The application also needs a size policy, content checks, private storage, and a way to remove incomplete work.
This guide builds a small, local endpoint for UTF-8 text files. It accepts one file of up to 32 KiB, caps the entire request body at 64 KiB, and generates its own storage location. The narrow format makes the behavior inspectable. An image, PDF, or archive endpoint needs its own format-aware validation.
Send files through the application when it needs to inspect or transform their contents before accepting them. That path uses application bandwidth, memory, temporary storage, and processing time. For large files, consider letting an authorized client upload directly to a private object-storage destination, then processing the result separately.
Our S3 presigned URL guide covers temporary signed uploads and downloads for Amazon S3. A signed upload still needs an application decision about the user, destination, and permitted operation. Verify the specific API behavior before applying that design to another provider.
The example here has no authentication and binds only to a loopback address. Keep it private. Before exposing an upload endpoint, add access control, per-user quotas, request deadlines, retention rules, and the content checks required by its actual purpose.
FastAPI's file-upload documentation distinguishes a file read into bytes from an UploadFile backed by a spooled temporary file. Spooling can move file data from memory to disk; it does not establish an upload-size policy.
We use two limits. The outer guard counts the bytes of the whole multipart body before parsing it. The endpoint then counts the file's bytes while reading it. Multipart boundaries, headers, and any other form content count toward the body limit, so the two limits should not be identical.
The tested versions are FastAPI 0.163.1, Starlette 1.10.0, python-multipart 0.0.34, HTTPX 0.28.1, and Uvicorn 0.54.0, with Python 3.12.14 on Windows. Install them in a dedicated virtual environment:
python -m pip install fastapi==0.163.1 starlette==1.10.0 python-multipart==0.0.34 uvicorn==0.54.0 httpx==0.28.1
The installed FastAPI constructor rejected max_body_size. This example therefore uses the explicit guard below instead of assuming a newer documentation example works in the pinned release. Save it as body_limit.py.
"""Small-body ASGI guard: buffer at most the configured cap before parsing."""
from starlette.responses import JSONResponse
class BodyLimit:
def __init__(self, app, limit):
self.app, self.limit = app, limit
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
chunks, size = [], 0
while True:
message = await receive()
if message["type"] == "http.disconnect":
return
chunk = message.get("body", b"")
size += len(chunk)
if size > self.limit:
response = JSONResponse({"detail": "Request body exceeds 64 KiB"}, status_code=413)
return await response(scope, receive, send)
chunks.append(chunk)
if not message.get("more_body", False):
break
body = b"".join(chunks)
delivered = False
async def replay():
nonlocal delivered
if not delivered:
delivered = True
return {"type": "http.request", "body": body, "more_body": False}
return await receive()
await self.app(scope, replay, send)
This guard buffers the accepted body before passing it to the application. The 64 KiB setting is a request limit, not a claim that total process memory is 64 KiB: joining buffers, parsing, and concurrent requests add overhead. This is a small-file example, not a streaming design for multi-gigabyte uploads. It counts received bytes even when the client omits Content-Length.
Save the following as upload_app.py beside the guard. The endpoint uses request.form() to set parser limits explicitly: one file and no ordinary text fields. It requires that file to be named file. Because this example parses the request manually, it does not automatically create a file-upload widget in Swagger UI; use the request command below.
"""Private local example: bounded UTF-8 plain-text uploads, not a public service."""
import codecs
import os
import tempfile
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request
from starlette.concurrency import run_in_threadpool
from starlette.datastructures import UploadFile
from body_limit import BodyLimit
MAX_BODY = 64 * 1024
MAX_FILE = 32 * 1024
CHUNK = 8 * 1024
def create_app(root: Path):
root = root.resolve()
root.mkdir(parents=True, exist_ok=True)
app = FastAPI()
@app.post("/uploads", status_code=201)
async def upload(request: Request):
async with request.form(max_files=1, max_fields=0) as form:
file = form.get("file")
if not isinstance(file, UploadFile):
raise HTTPException(422, "One file field named file is required")
return await run_in_threadpool(store_text, file)
def store_text(file: UploadFile):
folder = None
committed = False
try:
media_type = (file.content_type or "").split(";", 1)[0].lower()
if media_type != "text/plain":
raise HTTPException(415, "This example accepts plain text only")
folder = Path(tempfile.mkdtemp(prefix="upload-", dir=root))
pending = folder / "pending.part"
decoder = codecs.getincrementaldecoder("utf-8")("strict")
total = 0
with pending.open("xb") as destination:
while chunk := file.file.read(CHUNK):
total += len(chunk)
if total > MAX_FILE:
raise HTTPException(413, "File exceeds 32 KiB")
text = decoder.decode(chunk)
if any((ord(c) < 32 and c not in "\t\r\n") or ord(c) == 127 for c in text):
raise HTTPException(422, "Disallowed control character")
destination.write(chunk)
decoder.decode(b"", final=True)
if total == 0:
raise HTTPException(422, "Empty file")
# The directory is server-generated. The supplied filename is never a path.
os.replace(pending, folder / "content.txt")
committed = True
return {"upload_id": folder.name, "bytes": total}
except UnicodeDecodeError:
raise HTTPException(422, "File is not valid UTF-8") from None
finally:
file.file.close()
if folder is not None and not committed:
(folder / "pending.part").unlink(missing_ok=True)
folder.rmdir()
return BodyLimit(app, MAX_BODY)
def make_app():
# Use a dedicated directory outside any public document root.
return create_app(Path(os.environ.get("UPLOAD_ROOT", "./private-uploads")))
The declared media type must be text/plain, but that header is client-supplied. The example also decodes the bytes as UTF-8 and rejects empty files and selected control characters. Its incremental decoder handles a multibyte character split between reads and rejects an incomplete sequence at the end.
These checks establish the example's text contract. They do not prove that a file is harmless: valid UTF-8 can contain HTML, scripts, or misleading text. Do not execute uploaded content or expose this directory as a public static-files directory. A production document pipeline may need quarantine, scanning, and format-specific inspection before another component processes the file.
The application ignores the supplied filename when writing to disk. It creates a new server-generated directory and uses the fixed name content.txt inside it. Repeated uploads with the same client filename therefore receive distinct upload IDs. A client-provided path such as ../../outside.txt never becomes a filesystem destination.
The accepted contents are first written to pending.part. Once validation and the write finish, the file is closed and renamed. Ordinary validation or finalization failures remove the partial file and its directory; parsed-file handles are also closed. Python's temporary-file documentation explains the generated-name facilities used here.
A successful response means this local write completed. It does not establish crash durability, a backup, or replication. Process termination can bypass cleanup, and disk failures can prevent it. Use a dedicated directory owned by the service, account for abandoned uploads, and decide how accepted files become durable before treating this as an application-storage design.
Start the server from the directory containing both Python files:
python -m uvicorn upload_app:make_app --factory --host 127.0.0.1 --port 8000
Create a small UTF-8 file named sample.txt, then send it from another terminal:
curl -F "file=@sample.txt;type=text/plain" http://127.0.0.1:8000/uploads
On Windows PowerShell, use curl.exe for the request command. A successful request returns HTTP 201 with an upload_id and byte count. The file is stored under private-uploads/<upload_id>/content.txt relative to the server's working directory. Set UPLOAD_ROOT to a dedicated private path if you need another location.
Inspect the saved bytes and response, then stop the local server with Ctrl+C. There is no download route, user account, or object-storage connection in this example. Its synchronous file writes run in a worker thread rather than directly inside the asynchronous route.
On November 19, 2026, 45 functional checks passed against this code. They used FastAPI's local test client and a separately started Uvicorn server on 127.0.0.1. The latter received real HTTP/1.1 chunked uploads without a Content-Length header.
| Case | Observed result |
|---|---|
| Valid text and an exact 32 KiB file | 201; stored bytes and returned sizes verified |
| Repeated and path-like client filenames | Distinct server-generated locations; no path escape observed |
| Empty, invalid UTF-8, or disallowed control bytes | 422; no retained partial upload |
| Wrong declared media type | 415 |
| File above 32 KiB | 413; no retained partial upload |
| Extra file or ordinary form field | 400; parser-created temporary files closed |
| Simulated finalization failure | 500; partial file removed; internal error details omitted |
| Chunked HTTP without Content-Length | Valid request: 201; body above 64 KiB: 413 |
The checks also verified closure of parser-created temporary files and shutdown of the test server. The HTTPX-based test client emitted a deprecation warning in this Starlette release; the pinned combination still passed, and the separate HTTP tests exercised the body limit outside that client.
No public traffic, authentication flow, malware scanner, Linux deployment, object-storage API, crash recovery, or load benchmark was tested. A byte limit does not impose a deadline on a slow sender. Validate proxy and server timeouts, concurrency, storage permissions, and failure recovery in the deployment you intend to run.
A local disk can suit a private demonstration, but another application instance will not automatically see its files. Our application-storage guide explains the choices for durable data. For the HTTP service itself, compare operating responsibilities in the API-hosting guide, then use the FastAPI deployment guide when planning the deployment.
CPU instances with Hivenet are a relevant option for running an upload API and its processing jobs. You manage the application, dependencies, access controls, quotas, and monitoring. Size the instance from measured workload behavior, including concurrent uploads and temporary-disk use.
For durable application files, Hivenet Object Storage provides a separate S3-compatible storage path with a request-access option. Verify your required operations, permissions, upload failure handling, and retrieval flow before integration. The local example above does not establish those results or claim that every Amazon S3 feature is available.
Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.