Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Backend vs Frontend: What Runs Where, and Why the Server Is the One You Trust
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • File Upload and Download in FastAPI: multipart, UploadFile and FileResponse
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  • A Layered FastAPI Project: Controllers, Services, Schemas and One Folder per Concern
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider
  • Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask
  • How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak
  • AWS Cognito vs Keycloak: User Pools, App Clients and When a Managed Identity Provider Wins
  • Migrating FastAPI from Keycloak to AWS Cognito: The Four Values, the JWKS Address and Every Check on an Access Token
  • Testing a Cognito Login End to End: Allow the Password Flow, Confirm the Email Code, and Reset a Forgotten Password
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  • Testing a FastAPI Blog with pytest: a Test Database through dependency_overrides, Login Fixtures and Reading a Failure
  • Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Fundamentals

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

One request through the layers GET /api/v1/hello router.py controller thin service the logic schema JSON shape Depends(get_hello_service) {"message": "hello world"}
The controller stays thin, the service holds the logic, and the schema shapes the JSON that goes back.

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 fileWhat 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.pyApp 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:

FastAPIDjangoFlask
LayoutOne app package, eight foldersA project, mywebsite, and an app, myappapp with six folders, no api or auth folder
Settingsconfig.py, one Settings classsettings.py with dictionaries like COGNITO and S3; Celery settings start with CELERYconfig.py
RoutesAPIRouter per controller, gathered in router.pyTwo urls.py files; function views with api_viewBlueprints with MethodView classes, one method per HTTP verb
DependenciesDependsOne authentication class set in settingsDone by hand: require_auth, S3Service(), SessionLocal with a finally
SchemasPydanticDRF serializers in utilsmarshmallow
TableCreated at startupA migration creates myapp_projectCreated inside create_app
Serveruvicornmain.py runs migrate, then the Django servergunicorn 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.py starts Uvicorn, and create_app mounts 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 21 of 39

Previous
Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
Next post
FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose

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.

On this page

  • Two main.py files
  • Controller, service, schema
  • Run it
  • The finished backend, folder by folder
  • Models are for the database, schemas are for the API
  • A controller asks, a service does the work
  • The same app in Django and Flask
  • Why the map matters
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.