A Layered FastAPI Project: Controllers, Services, Schemas and One Folder per Concern
Start a FastAPI backend from a clean skeleton (main.py, create_app, a router under /api/v1, a thin controller, a service and a Pydantic schema), then read the finished subtitle backend folder by folder, with the Django and Flask layouts side by side.
What you will learn
- Start a FastAPI app with an outer main.py and a create_app factory
- Follow a request from controller to service to schema
- Read a finished backend folder by folder and know where each change goes
- Spot how Django and Flask lay out the same app differently
Before you start
- FastAPI Hello World
- Basic Python classes
A backend that will later take sign in, uploads and subtitles needs a skeleton that's easy to grow. This one has one entry file, one first route, and a folder for each job. Every endpoint added later follows the same pattern, so it's worth getting right before anything else plugs in.
Two main.py files
The outer main.py only starts the server. It calls uvicorn.run with app.main:app, and the host, port and reload flag come from config.py. Debug is on, so the server reloads every time you save.
import uvicorn
from app.config import settings
if __name__ == "__main__":
uvicorn.run(
"app.main:app",
host=settings.host,
port=settings.port,
reload=settings.debug,
)
The inner app/main.py builds the app in a create_app function, adds the docs page at /docs, and mounts every route under the prefix /api/v1:
def create_app() -> FastAPI:
app = FastAPI(
title=settings.app_name,
version=settings.app_version,
description=settings.app_description,
docs_url=None,
redoc_url=None,
)
@app.get("/docs", include_in_schema=False)
def swagger_ui():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=settings.app_name,
swagger_js_url=settings.swagger_ui_js,
swagger_css_url=settings.swagger_ui_css,
)
app.include_router(api_router, prefix=settings.api_prefix)
return app
app = create_app()
The title is "StudyEasy Application" and the version 1.0.0, both from the settings.
Controller, service, schema
router.py registers each controller:
from fastapi import APIRouter
from app.controllers import hello_controller
api_router = APIRouter()
api_router.include_router(hello_controller.router)
The controller's prefix is /hello with the tag Greetings. Add the API prefix and the full path is /api/v1/hello. The function asks for a HelloService with Depends, so FastAPI calls get_hello_service and passes the result in:
router = APIRouter(prefix="/hello", tags=["Greetings"])
def get_hello_service() -> HelloService:
return HelloService()
@router.get(
"",
response_model=HelloResponse,
summary="Hello World",
operation_id="hello_world",
)
def hello_world(
service: HelloService = Depends(get_hello_service),
) -> HelloResponse:
return service.get_greeting()
The service does the work, and the schema is a Pydantic model with one field:
class HelloService:
def get_greeting(self) -> HelloResponse:
return HelloResponse(message="hello world")
class HelloResponse(BaseModel):
message: str = Field(..., examples=["hello world"])
More on Depends and swapping services in tests is in dependency injection with FastAPI Depends.
Run it
python main.py starts Uvicorn on 127.0.0.1, port 8000. Open /api/v1/hello and the JSON comes back:
{"message": "hello world"}
The root path on its own gives a 404, because no route sits there. Open /docs and Swagger lists StudyEasy Application 1.0.0 with GET /api/v1/hello under Greetings. Try it out, Execute, and you get code 200 with the same message. You can test every new route here before the front end ever calls it.
The finished backend, folder by folder
Once the subtitle app has sign in, uploads, Celery and Whisper, the same skeleton has grown into eight folders under app, each holding one concern:
| Folder or file | What sits there |
|---|---|
api/ | router.py, seven lines that gather the hello and projects controllers |
auth/ | cognito.py: talks to Cognito and checks the token |
controllers/ | The routes: hello, auth, me, projects |
db/ | session.py: the engine, a session maker and get_db |
models/ | project.py: the ORM class for the projects table |
schemas/ | Pydantic shapes for requests and responses |
services/ | project_service.py and s3_service.py: the business logic |
tasks/ | transcribe.py: the background job |
main.py, config.py, celery_app.py, whisper_loader.py | App factory, settings, the Celery app, the model loader |
The inner main.py has grown too. It adds CORS and a health route, creates the tables at startup, includes the API router under /api/v1, and includes the auth controller directly, so those routes start with /auth. So the inner main is the place to look when you want to know which routes exist.
Models are for the database, schemas are for the API
Project in models/project.py maps to the projects table: id, user sub, file name, status, progress, the two S3 keys and the times. SQLAlchemy turns a Project object into a row and back. Schemas are different. ProjectSummary is what the list route sends back, and ProjectCreateResponse is only the id and the status:
class ProjectCreateResponse(BaseModel):
id: str
status: str
Keep those two apart. The table can gain a column without the API changing, and the API can hide a column the browser shouldn't see.
A controller asks, a service does the work
project_service.py has the database steps: create project, list for user, update status, update progress, set SRT key and delete project. s3_service.py wraps the bucket. The upload route in projects_controller.py gets three dependencies filled before it runs:
def create_project(
file: UploadFile = File(...),
language: str | None = Form(default=None),
db: Session = Depends(get_db),
claims: dict[str, Any] = Depends(get_current_user),
s3: S3Service = Depends(get_s3_service),
) -> ProjectCreateResponse:
So a request goes router, controller, services, and then Redis. A job goes worker, task, Whisper, S3, and back to the same database row. That flow is in wiring Whisper, Celery and S3 into the app.
The same app in Django and Flask
The routes and the JSON stay the same in all three, so the React app doesn't change. Only the places change:
| FastAPI | Django | Flask | |
|---|---|---|---|
| Layout | One app package, eight folders | A project, mywebsite, and an app, myapp | app with six folders, no api or auth folder |
| Settings | config.py, one Settings class | settings.py with dictionaries like COGNITO and S3; Celery settings start with CELERY | config.py |
| Routes | APIRouter per controller, gathered in router.py | Two urls.py files; function views with api_view | Blueprints with MethodView classes, one method per HTTP verb |
| Dependencies | Depends | One authentication class set in settings | Done by hand: require_auth, S3Service(), SessionLocal with a finally |
| Schemas | Pydantic | DRF serializers in utils | marshmallow |
| Table | Created at startup | A migration creates myapp_project | Created inside create_app |
| Server | uvicorn | main.py runs migrate, then the Django server | gunicorn with main:app |
One more Django difference: the upload creates the row first, then uploads to S3, then sets QUEUED and sends the task. The answer is still a 201 with QUEUED. And its Celery app sits in mywebsite/celery.py, with the task in myapp/celery, so the worker starts with celery -A mywebsite.
Why the map matters
AI tools can write a lot of this code, but a change in the wrong place can break something else. In a production app you want small changes, one file at a time. Say you want the upload to accept only audio and video files. You already know that check belongs in the projects controller. So you open a new chat, paste that one file, and say exactly what to change: you're a FastAPI developer, here is this file and its create_project route, reject other file types with a clear error and change nothing else, give me the full updated file. Then you read the change line by line.
Common mistakes
- Putting logic in the controller. Keep it in a service so it can be tested and reused.
- Returning the ORM model as the API response. Map it to a schema.
- Forgetting to register a new controller in
router.py, then wondering why the route is a 404.
Quick recap
- The outer
main.pystarts Uvicorn, andcreate_appmounts the routes under/api/v1. - A request goes controller, service, schema.
- One concern per folder means you can guess where code sits before opening a file.
Try it yourself
Add a goodbye endpoint the same way, with a schema, a service and a controller, then register it in router.py and call it from /docs.
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
FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.
RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.
