Private S3 Uploads from FastAPI: A Locked Bucket, a Key per User, and Presigned Links That Expire
Uploaded files don't belong on the server's disk. Create a private S3 bucket, stream each upload into it with boto3 under uploads/user/id/file, refuse non-media files with a 415, and read files back through presigned links that last 900 seconds and only for the owner.
What you will learn
- Create a private S3 bucket with block all public access
- Stream an upload into S3 with boto3 under a key that includes the user's ID
- Reject anything that isn't audio or video with a 415
- Give each user a fifteen-minute presigned link to their own file and nobody else's
Before you start
- Migrating FastAPI from Keycloak to AWS Cognito
- A layered FastAPI project
Before Whisper can listen to anything, the uploaded file needs a home. The user picks a file in the browser and it's sent to the FastAPI backend. It doesn't stay on the server's disk. It goes into Amazon S3, a storage service in AWS, where any part of the app can read it later, including the step that runs Whisper on it. (What Whisper is and how to run it is in running Whisper as a script.)
Three words first. S3 keeps files in a bucket. Each file is an object. Its full path inside the bucket is the key.
Create a private bucket
- In the AWS console, search for S3 and open it. On the Buckets page, click create bucket.
- Keep the bucket type general purpose.
- Give it a name: 3 to 63 characters, only lowercase letters, numbers, dots and hyphens, and unique across all of AWS, not just your account.
- Keep object ownership on ACLs disabled, the recommended option.
- Keep block all public access ticked. The files are private, and only the backend should read them.
- Click create bucket.
The access key the app uses for this bucket comes from IAM and goes into the .env file. Never paste it into code.
Settings and the S3 service
config.py gets the S3 settings:
# S3
s3_bucket: str = ""
s3_upload_prefix: str = "uploads/"
s3_subtitle_prefix: str = "subtitles/"
s3_presign_ttl_seconds: int = 900
s3_bucket is the bucket you just created, every upload lands under uploads/, and 900 is the life of a presigned link in seconds. The service wraps a boto3 client (boto3 is the AWS library for Python). Here it is as it stands once the full pipeline is built, with the subtitle helpers alongside:
class S3Service:
def __init__(self) -> None:
self._client = boto3.client("s3", region_name=settings.aws_region)
self._bucket = settings.s3_bucket
def upload_fileobj(self, key: str, fileobj: BinaryIO, content_type: str | None = None) -> None:
extra = {"ContentType": content_type} if content_type else {}
self._client.upload_fileobj(fileobj, self._bucket, key, ExtraArgs=extra)
def download_to_path(self, key: str, dest_path: str) -> None:
self._client.download_file(self._bucket, key, dest_path)
def presign_get(self, key: str, ttl_seconds: int | None = None) -> str:
return self._client.generate_presigned_url(
"get_object",
Params={"Bucket": self._bucket, "Key": key},
ExpiresIn=ttl_seconds or settings.s3_presign_ttl_seconds,
)
upload_fileobj takes a key and an open file and streams the file into the bucket with its content type. presign_get makes a time-limited link to one object. In the first version an extra endpoint URL setting stays empty for AWS and is filled only for a local test.
The upload endpoint
uploads_controller.py has the prefix /uploads and is added in router.py next to the hello router, so the full path is /api/v1/uploads. The POST answers 201 Created. It takes the file, the user's claims from get_current_user (the Cognito token check) and the S3 service, then:
- Cleans the file name and checks the extension against the allowed list: mp3, wav, m4a, mp4, mov, mkv and webm. Anything else gets a 415, "Upload an audio or video file".
- Builds the key:
uploads/, then the user's ID from the token, then a fresh random upload ID, then the file name. - Puts the file into the bucket and returns the ID, the key, the file name and the size.
Test it without AWS
For the test, the bucket was moto, a local copy of the S3 API. boto3 makes the same calls, but no AWS account is needed.
| Request | Answer |
|---|---|
| Upload with no token | 401, Not authenticated |
Upload sample.wav with a valid token | 201, with the ID and the key uploads/test-user-1/<upload id>/sample.wav |
| List the bucket | Exactly one object under that key, its size in bytes matching the file sent |
Upload notes.txt | 415, Upload an audio or video file |
So only signed-in users can upload, and only audio or video goes in.
Reading a file back: a presigned link
The bucket is private, so how does anyone read a file? They ask the second endpoint, /uploads/url, with the key. It first checks that the key starts with uploads/ and your own user ID. If it's someone else's file, the answer is 403, Not your file. If it's yours, you get a presigned link. It has a signature in it, and it works for 900 seconds, fifteen minutes. Opening that link returned exactly the same bytes that were uploaded.
The browser downloads straight from S3 with that link, never through the backend. When a page reads the file with fetch instead of a plain download, S3 also needs a CORS rule; that's in the S3 CORS rule.
In the S3 console, uploads from the finished app sit under the uploads folder, each in its own folder named with a long ID, with the audio file inside (one here was 8.2 MB).
Common mistakes
- Unticking block public access "to make the links work". Presigned links work on a private bucket; that's the point of them.
- Building the key from the file name alone. Two users with
sample.wavoverwrite each other. - Signing a link for any key the client sends. Check the prefix against the user's ID first.
- Long link lifetimes. Fifteen minutes is plenty for a download.
Quick recap
- Uploads go into a private S3 bucket, not onto the server.
- The key is
uploads/<user>/<upload id>/<file>. - Bad types get 415; other users' files get 403.
- A presigned GET link reads a file back for fifteen minutes.
Try it yourself
Add .flac to the allowed extensions, upload a flac file, and check the key in the response.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
