Project structure · Backend
FastAPI project structure
Opens with creditsA typed Python API for an orders app, built the way the FastAPI docs and the official full stack template lay it out: one app package, a router per feature, Pydantic schemas at the edges, services in the middle and SQLAlchemy models with Alembic migrations underneath. For students who have finished the FastAPI tutorial and want to know where the second, tenth and fiftieth file go.
How it grows
Each stage opens the explorer there
- 1Day 1What the scaffold and your first hour give you12 files and folders
- 2GrowingWhat a real app with features and tests adds+91 files and folders
- ProductionWhat running it for real users adds+42 files and foldersOpens with credits
- ExpertWhat a team needs to keep it healthy for years+43 files and foldersOpens with credits
How it is organised
- One `app` package holds all the code, so imports look the same in the dev server, the tests and the container.
- Split by layer, one file per feature in each layer: `api/routes/orders.py`, `schemas/order.py`, `services/orders.py`, `db/models/order.py`. This is the layout the FastAPI docs and the official template use. Past roughly ten features, many teams switch to one folder per feature (`orders/router.py`, `orders/schemas.py`); both are fine, mixing them is not.
- Routes stay thin: they parse input, call a service and return a schema. Business rules live in services, which know nothing about HTTP.
- Pydantic schemas are the API contract; SQLAlchemy models are the database shape. Keep them separate even when they look alike today.
- Every setting comes from the environment through one `Settings` class. Nothing secret is written in code or committed.
- Shared things (database session, current user, settings) arrive through `Depends`, so tests can swap them with `app.dependency_overrides`.
- Queries live in repositories, rules and transactions in services. Services are tested fast with factories; repositories and migrations are tested against a real PostgreSQL in a container.
- Slow or retryable work (emails, webhooks, reports) leaves the request through a Celery task that receives ids, never ORM objects.
- Tests grow in layers: fast unit tests at Growing, API tests on every push, integration tests on real PostgreSQL at Production, contract, load and mutation tests at Expert.
- Every tool reads its settings from pyproject.toml where it can, and the Makefile, pre-commit and CI call the same commands, so "it passed locally" means it passes in CI.
At the top of the project
Open one in the explorer for the full story
- orders-api/
- .venv/The project virtual environment that uv creates and keeps in sync with uv.lock.
- .git/Git history for the project, created by `git init`.
- .gitignoreTells Git which files never to commit: the venv, caches, .env and local databases.
- .python-versionPins the Python version uv uses for this project, for example 3.14.
- .editorconfigIndentation, line endings and final newline rules every editor understands.
- pyproject.tomlProject metadata, dependencies, and settings for FastAPI CLI, pytest and Ruff in one file.
- uv.lockThe exact version of every package, direct and indirect, written by uv.
- README.mdHow to run, test and deploy the project, for the next person and for future you.
- app/The application package: every line of your API lives under here.11 inside
- alembic/Database migrations: versioned scripts that change the schema step by step.4 inside
- alembic.iniAlembic settings: where the scripts live, the file name template, logging.
- tests/pytest tests in layers: unit, API, integration on real PostgreSQL, end to end and contract tests.6 inside
- .pytest_cache/pytest's cache of the last run, used by `--lf` to rerun failures.
- .ruff_cache/Ruff's cache of files it already checked, so the next run only looks at changes.
- .mypy_cache/mypy's incremental type information, which makes the second run much faster.
- .coverageThe raw coverage data `pytest --cov` writes after a run.
- htmlcov/A browsable HTML coverage report from `pytest --cov-report=html`.
- .envYour local values for the settings: database URL, secrets, debug flags.
- .env.exampleEvery setting the app needs, with safe placeholder values. Committed.
- compose.yamlRuns PostgreSQL and Redis locally with one `docker compose up -d`.
- MakefileShort names for the commands everyone runs: install, dev, worker, test, lint, migrate, seed.
- .pre-commit-config.yamlRuns Ruff, a uv.lock check, a secret scanner and mypy before each commit.
- .vscode/Shared VS Code settings, recommended extensions and debug configurations.3 inside
- .devcontainer/A Dev Container definition: the whole toolchain in a container, for VS Code or Codespaces.1 inside
- AGENTS.mdInstructions for AI coding agents: how to run, test and where things go.
- CLAUDE.mdPoints Claude Code at AGENTS.md so both tools share one set of rules.
Learn more on Sefism
Roadmaps, cheat sheets and projects that go with FastAPI.
- Roadmap· PythonBackend development roadmapAPIs, databases, auth, deploys
- RoadmapSQL and databases roadmapQueries, design, indexes, transactions
- RoadmapDevOps and cloud roadmapLinux, Docker, Kubernetes, AWS
- Cheat sheetBackend development cheat sheetAPIs, databases, auth, deploys.
- Cheat sheetSQL and databases cheat sheetQueries, design, indexes, transactions.
- FYP idea· BeginnerTuition Centre Fee and Attendance Manager with Parent RemindersA web app for small tuition centres and academies to manage batches, take attendance from a phone, generate monthly fee vouchers and send parents reminders. A beginner-friendly final year project with a real paying customer in almost every neighbourhood.
- FYP idea· AdvancedSandboxed Spreadsheet Analyst Agent for Small Business OwnersBuild an agent that answers a shop owner's questions about their messy Excel and CSV files by writing and running Python in an isolated sandbox, then returns a chart, a plain-language answer and the exact script it ran. The project is about safe code execution, cost limits, reproducibility and trajectory evals on real-world data, not about a chat interface.
- FYP idea· IntermediatePolicy-Bound Returns and Refunds Agent for Small Online StoresA final year project that builds an LLM agent for small online stores which handles return, exchange and refund requests through real store tools, while a separate policy layer blocks any action the store policy does not allow. You test it with simulated customers and measure policy violations, not just completed chats.
- QuestionI understand tutorials but cannot build anything myself. Why does coding feel so different when I am alone?Tutorials train recognition, not production. When you follow along, someone else makes every decision. Building alone requires you to break a problem down and make choices, which is a separate skill. Build it with small projects, planning on paper first, and a rule to struggle before you look anything up.
See 7 moreShow fewer
- QuestionI am graduating soon and feel like I learned four years of theory but cannot actually build software. What now?The gap between theory and building is common and closable. Building is a separate skill: breaking a vague idea into small steps, using real tools and finishing. Close it with one guided build, then one project you design yourself, shipped in small working slices. Your theory will start to make sense along the way.
- QuestionHow do I learn Git and GitHub properly instead of just copying commands?Learn the model first: commits are snapshots, branches are pointers, and remotes are copies. Then use Git daily on your own projects, practise a team workflow with branches and pull requests, and break things on purpose, such as merge conflicts, so you learn to recover calmly.
- Resource· GuideFastAPI Tutorial: User GuideThe official FastAPI tutorial and user guide builds an API one concept at a time: path and query parameters, request bodies with Pydantic validation, response models, error handling, dependency injection, OAuth2 with hashed passwords and JWT, SQL databases, bigger applications, background tasks and testing. One of the few framework docs that doubles as a genuinely good backend course, for Python developers building modern APIs.
- Resource· GuidePydantic DocumentationThe official docs for Pydantic, Python's most widely used data validation library: models declared with type hints, strict and lax validation, JSON Schema generation and serialisation. It is how Python agents validate model output and tool arguments, and most agent frameworks accept Pydantic models directly.
- Resource· Guidepytest DocumentationThe official documentation for pytest, the most widely used Python testing framework. It shows how to write tests as plain functions with ordinary assert statements, share setup through fixtures, run one test against many inputs, and extend the tool with plugins. The twenty-minute getting started guide is enough to put tests around a small project, and the rest works as a reference as your suite grows.
- Resource· GuideDocker Docs: Get StartedDocker's official starting point: install Docker, follow a tutorial that builds, runs and shares a containerised application, then work through short concept pages on containers, images, registries, Compose, image layers, Dockerfiles, the build cache, multi-stage builds, ports and persistent data. It suits developers who have heard of containers but never used them, and it is current, free and more accurate than most tutorials copied from it.
- Resource· GuideOWASP API Security Top 10The OWASP API Security Top 10 (2023 edition) lists the most critical security risks in APIs, led by broken object level authorisation, broken authentication and broken object property level authorisation. Each risk comes with attack scenarios and prevention advice. It suits anyone building or reviewing backends, because these flaws are common, easy to miss in code review and often invisible in normal testing.
Checked against 23 official sources, October 2026. If something has changed, the docs win.Show sourcesHide sources
- FastAPI: Bigger Applications, Multiple Files
- FastAPI: Settings and Environment Variables
- FastAPI: Testing
- FastAPI: FastAPI in Containers (Docker)
- fastapi-new (official project generator)
- Full Stack FastAPI Template
- uv: Creating projects
- uv: Using uv in Docker
- Alembic tutorial
- SQLAlchemy 2 ORM quick start
- FastAPI: OAuth2 with Password and JWT
- uv: Using uv in GitHub Actions
- uv: Using uv with pre-commit
- Celery documentation
- factory_boy: Using factory_boy with ORMs
- Testcontainers for Python
- structlog documentation
- OpenTelemetry Python
- Sentry for FastAPI
- import-linter documentation
- Schemathesis documentation
- Locust documentation
- mutmut documentation
Best practices and checklists for this stack
Picked from the other libraries by shared topics.
Best practices
See all- REST API Design Best PracticesDesign HTTP APIs clients enjoy using: resources and URLs, methods, status codes, problem details errors, pagination, idempotency keys, ETags, versioning and OpenAPI.
- TypeScript Best PracticesModern TypeScript best practices for 2026: strict settings, TypeScript 7, modeling data with unions, safe narrowing, runtime validation, generics and typed linting.
- Authentication Best PracticesBuild sign-in that holds up: password rules from NIST, Argon2id hashing, login throttling, MFA and passkeys, secure sessions and safe account recovery.
Checklists
See all- Database Migration ChecklistCheck a schema or data migration before it ships: expand and contract, lock behaviour, online indexes, batched backfills, rehearsal on real data, backups, rollback, deploy order and monitoring.
- Production Readiness ChecklistCheck a service before it takes real traffic: ownership, SLOs, capacity, timeouts and retries, alerts, rollout and rollback, backups, security and on-call.
- API Security ChecklistCheck your REST or GraphQL API against the OWASP API Security Top 10: authentication, object authorization, rate limits, input validation, SSRF, CORS and logging.
Stuck on something specific?
Writing only gets you so far. If you want an answer to your situation rather than the general case, book a session and we will work through it together. Sessions are free for approved Sefism members, and a few slots open each week.
- 1:1 Mentorship
- Fresh Graduate Mentorship
- Career Guidance
Brand deals, promos and partnerships: tauseeffayyaz@gmail.com