Stateless FastAPI Uploads with Amazon S3 Presigned URLs
How I stopped saving user uploads to my API's disk and moved them to a private S3 bucket with presigned POST URLs, with FastAPI code, an IAM checklist and the lessons I learned as a student.
Why I stopped saving files to my server
If your API saves user uploads to its own disk, it cannot scale past one instance. I learned this while building Postly, a small social posting API with FastAPI and PostgreSQL. My first version saved profile pictures to an
uploads/ folder next to the code. It worked on my laptop, then fell apart the moment I thought about running a second container.In this post I show how I moved uploads to Amazon S3 with presigned URLs, so the API stays stateless and the files never pass through it. Everything here is beginner-friendly: one bucket, one IAM policy and about 40 lines of Python.
The problem with uploads on the app server
Local disk storage creates three problems as soon as you deploy:
- Files disappear. Containers are disposable. A redeploy or a restarted task wipes everything in
uploads/.
- Instances disagree. With two containers behind a load balancer, a photo uploaded to instance A returns 404 when the next request hits instance B.
- The API does heavy lifting. Every image streams through your Python process, holding a worker busy while a slow phone connection uploads a few megabytes.
The fix is to treat the API as stateless: it stores references to files in PostgreSQL, and S3 stores the files themselves.
The architecture: presigned URLs
A presigned URL is a temporary link, signed with the API's AWS credentials, that lets the client upload one specific file to S3 without having any AWS keys of its own.
The flow has five steps:
- The client asks the API for a presigned POST.
- The client uploads the file directly to S3, bypassing the API.
- The client sends the file's key back to the API.
- The API verifies that the object exists in S3.
- The API saves the key in PostgreSQL.
The API never touches the file bytes: it signs a URL, then verifies and records the result.
Implementation in FastAPI
The whole feature is two endpoints: one hands out an upload URL, one confirms the upload.
1. Create a private bucket. Keep Block all public access turned on. Add a CORS rule that allows
POST from your frontend's origin, otherwise browsers will refuse the direct upload.2. Generate a presigned POST. A presigned POST (rather than a presigned PUT) lets S3 itself enforce the file size and type:
import uuidimport boto3from fastapi import APIRouter, Depends
router = APIRouter()s3 = boto3.client("s3", region_name="eu-central-1")BUCKET = "postly-avatars"MAX_BYTES = 5 * 1024 * 1024 # 5 MB
@router.post("/users/me/avatar/upload-url")def create_upload_url(user=Depends(get_current_user)): key = f"avatars/{user.id}/{uuid.uuid4()}.jpg" post = s3.generate_presigned_post( Bucket=BUCKET, Key=key, Fields={"Content-Type": "image/jpeg"}, Conditions=[ {"Content-Type": "image/jpeg"}, ["content-length-range", 1, MAX_BYTES], ], ExpiresIn=300, # 5 minutes ) return {"key": key, "url": post["url"], "fields": post["fields"]}The key is generated on the server, so a user can never overwrite someone else's file.
3. Upload from the client. The client sends a multipart form to
url with every entry of fields plus the file as the last field named file . The API is not involved in this request at all.4. Confirm and save the key. After the upload, the client calls the API with the key. The server checks the object really exists and belongs to this user, then stores it:
from botocore.exceptions import ClientErrorfrom fastapi import HTTPExceptionfrom pydantic import BaseModel
class AvatarConfirm(BaseModel): key: str
@router.put("/users/me/avatar")def confirm_avatar(body: AvatarConfirm, user=Depends(get_current_user), db=Depends(get_db)): if not body.key.startswith(f"avatars/{user.id}/"): raise HTTPException(403, "Not your file") try: s3.head_object(Bucket=BUCKET, Key=body.key) except ClientError: raise HTTPException(400, "Upload not found") user.avatar_key = body.key db.commit() return {"status": "ok"}5. Serve the image. Because the bucket is private, return a short-lived presigned GET URL when you send the profile:
def avatar_url(key: str) -> str: return s3.generate_presigned_url( "get_object", Params={"Bucket": BUCKET, "Key": key}, ExpiresIn=3600 )The database column
avatar_key is a plain string, added with one Alembic migration. No file bytes ever touch PostgreSQL or the API container.Security and cost checklist
- Least-privilege IAM. The API's role needs only
s3:PutObjectands3:GetObject(which also allowshead_object), and only onarn:aws:s3:::postly-avatars/avatars/*. Never give its3:*.
- No access keys in code. On ECS, Lambda or EC2, attach an IAM role; boto3 picks up its credentials automatically. Locally, use
aws configureor environment variables.
- Short expiry. Upload URLs live for 5 minutes, download URLs for 1 hour. A leaked link stops working quickly.
- Enforce size and type in S3. The
content-length-rangecondition rejects oversized files before they are stored, so nobody can fill your bucket with 2 GB uploads.
- Clean up orphans. If a user requests a URL but never confirms, the file is left behind. Upload to a
tmp/prefix first and add a lifecycle rule that deletestmp/objects after 1 day, or delete the old avatar when a new one is confirmed.
- Add CloudFront later. When traffic grows, put CloudFront in front of the bucket with Origin Access Control for caching and cheaper transfer.
What I learned
Moving uploads to S3 was a small change with a big effect on how I think about backends:
- State belongs in managed services. The API keeps only logic; PostgreSQL keeps records, S3 keeps files. Any container can now be killed or cloned.
- Let the client do the heavy transfer. Presigned URLs turn a slow, memory-hungry endpoint into two fast JSON calls.
- Validate at every boundary. Pydantic checks the request, S3 conditions check the file, and the server checks the key prefix before trusting anything.
If you are a student building your first API, try this pattern before you deploy: it is the difference between a project that runs on your laptop and one that can scale.
Have you used presigned PUT instead of POST, or switched to CloudFront signed URLs? Tell me in the comments what worked for you, and leave a like if this helped. I'm happy to write a follow-up on the frontend upload code.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article