FastAPI Project Structure & Database CRUD
How a real FastAPI project is split into files, connects to a database with SQLAlchemy, and exposes full CRUD endpoints.
What is it?
One main.py is fine for a two-route demo. A real FastAPI project splits the work across files, much like a layered Node.js app:
database.pysets up the database connection.models.pydefines the database tables as Python classes.schemas.pydefines the Pydantic models for what the API accepts and returns.- Router files group related endpoints.
main.pywires it all together.
SQLAlchemy is Python's most common tool for working with a relational database. Used as an ORM, it maps each row to a Python object, like Prisma or Sequelize in Node.
Explain like I'm 10
It's the same layered kitchen from backend project structure, relabeled for Python: routers are the host seating guests, path functions are the server taking the order, and SQLAlchemy models are the pantry holding the ingredients.
Examples
Project layout and the database connection
myapp/
├── main.py # creates the app, includes routers
├── database.py # engine + session setup
├── models.py # SQLAlchemy table definitions
├── schemas.py # Pydantic request/response shapes
└── routers/
└── items.py # /items endpoints
# database.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine("postgresql://user:password@localhost/mydb")
SessionLocal = sessionmaker(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()get_db is a FastAPI dependency. Because it uses yield, FastAPI runs the code before the yield, hands the session to the route, then runs the code after the yield (closing it) when the request finishes, even if the route raised an error.
Full CRUD endpoints using that session
# routers/items.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from .. import models, schemas
from ..database import get_db
router = APIRouter()
@router.post("/items", response_model=schemas.Item)
def create_item(item: schemas.ItemCreate, db: Session = Depends(get_db)):
db_item = models.Item(**item.dict())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@router.get("/items/{item_id}", response_model=schemas.Item)
def read_item(item_id: int, db: Session = Depends(get_db)):
item = db.query(models.Item).filter(models.Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
@router.put("/items/{item_id}", response_model=schemas.Item)
def update_item(item_id: int, updated: schemas.ItemCreate, db: Session = Depends(get_db)):
item = db.query(models.Item).filter(models.Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
for key, value in updated.dict().items():
setattr(item, key, value)
db.commit()
return item
@router.delete("/items/{item_id}")
def delete_item(item_id: int, db: Session = Depends(get_db)):
db.query(models.Item).filter(models.Item.id == item_id).delete()
db.commit()
return {"deleted": item_id}The four CRUD operations (Create, Read, Update, Delete) written with SQLAlchemy's query API instead of raw SQL, each wired to its own route.
Wrapping multiple changes in a transaction
@router.post("/transfer")
def transfer(from_id: int, to_id: int, amount: int, db: Session = Depends(get_db)):
try:
sender = db.query(models.Account).filter(models.Account.id == from_id).one()
receiver = db.query(models.Account).filter(models.Account.id == to_id).one()
sender.balance -= amount
receiver.balance += amount
db.commit()
except Exception:
db.rollback()
raise
return {"status": "ok"}Both balance changes must succeed or fail together. Nothing is written until db.commit() runs. If anything raises before that, db.rollback() discards both pending changes, so the accounts are never half-updated.
How it works
db: Session = Depends(get_db) uses FastAPI's dependency injection to call get_db for every request. Each request gets its own fresh session, used only for its queries, then closed.
Calls like db.add, db.commit, db.query, and .delete() map to INSERT, UPDATE/COMMIT, SELECT, and DELETE statements. SQLAlchemy generates them and sends them over the database connection, just as the pg driver does in Node.
To run the app, start an ASGI server pointed at it: uvicorn main:app --reload. It's the Python equivalent of node server.js, with --reload watching for changes during development.
Why does it exist?
It's the same reason a Node backend is split into routes/controllers/services/models. As endpoints and tables multiply, keeping setup, data shapes, and database logic each in one place keeps the project easy to navigate, instead of one tangled, growing file.
When to use it
Use this structure once a FastAPI project has more than a couple of endpoints or more than one table. It's the same point where you'd reach for a layered structure in Node.
When not to use it
For a two-endpoint script or quick prototype, separate database.py/models.py/schemas.py/router files are more scaffolding than you need. One main.py is easier to follow at that size.
Common mistakes
Forgetting db.commit() after db.add() or a change, so it stays staged in the session and never reaches the database.
Reusing one global session for every request instead of a fresh one per request via Depends(get_db). It can leak stale data or connections between unrelated requests.
Returning a raw SQLAlchemy model instead of going through a Pydantic response_model, which exposes internal fields (like a password hash) to the client.
Practice exercises
- Easy:
Which file (database.py, models.py, schemas.py, or a router) should a new 'orders' table definition go in?
- Medium:
Write a DELETE /items/{item_id} endpoint that returns a 404 if the item doesn't exist before deleting it.
- Hard:
Explain what would go wrong if one database session, created at app startup, were reused for every request instead of one session per request.
Interview questions
What does Depends(get_db) provide to a FastAPI route?
A fresh, request-scoped SQLAlchemy session that's closed automatically afterward. It's similar to Express middleware attaching something to the request object.
What command actually runs a FastAPI app?
uvicorn main:app --reload. That's an ASGI server pointed at the FastAPI instance, with --reload restarting it on code changes during development.
Why use a Pydantic response_model instead of returning the raw database object?
It controls exactly which fields reach the client, so internal-only fields don't leak into the response.
Why is `get_db` written as a generator function using `yield` instead of just returning a session directly?
FastAPI treats a dependency that uses yield as needing cleanup. It runs the code before yield to create the session and hands it to the route. When the route finishes, whether it succeeds or raises, FastAPI resumes the generator to run the code after yield. So db.close() always runs exactly once per request.
What would happen if `db.close()` were forgotten inside get_db's finally block?
The session and its database connection would never go back to the pool. Since get_db runs per request, the leak grows with every request until the pool is exhausted, just like forgetting client.release() with a raw Node driver.
In the create_item example, why is `db.refresh(db_item)` called after `db.commit()`?
After commit, the in-memory db_item may not include values the database generated or defaulted during the insert, like an auto-incrementing id. db.refresh() reloads the row into the same object so the response includes them.
What happens if `db.commit()` is never called after `db.add()` or after mutating an already-loaded object's attributes?
The change stays staged in the session's memory and is never written to the database. No error is raised, so the request seems to succeed while the data silently isn't saved. That's a confusing bug to track down.
Why does update_item use `setattr(item, key, value)` in a loop instead of just assigning `item = updated`?
item is a model instance SQLAlchemy is tracking, tied to a specific row in the session. Replacing it with updated, a plain Pydantic object, loses that tracking, so SQLAlchemy can't tell what changed. Setting attributes on the tracked object lets SQLAlchemy detect which fields changed and generate the right UPDATE.
What's the purpose of the response_model argument in a route decorator, like `@router.post("/items", response_model=schemas.Item)`?
FastAPI validates and shapes whatever the route returns against that Pydantic model before responding, dropping any field not declared on it. Even if the route returns a raw SQLAlchemy object with extra internal fields, only the declared fields reach the client.
Why does the example define separate schemas.Item and schemas.ItemCreate models, rather than one shared model for both input and output?
Input and output often need different shapes. Creating an item may not need or allow a client-supplied id, while reading one back should include the database-generated id. Separate schemas let each direction declare exactly the right fields.
What SQL statement does `db.query(models.Item).filter(models.Item.id == item_id).first()` correspond to?
Roughly SELECT * FROM items WHERE id = :item_id LIMIT 1. SQLAlchemy builds that SQL from the chained calls. .first() returns at most one row, or None if nothing matches, instead of raising.
Why does read_item explicitly check `if not item: raise HTTPException(status_code=404, ...)` instead of just returning whatever .first() produced?
.first() returns None when nothing matches instead of raising. Without the check, a request for a missing item would try to return None through the response_model and produce a confusing validation error instead of a clear 404.
What's the SQLAlchemy equivalent of the raw-SQL transaction pattern of BEGIN, commit, and ROLLBACK shown for the money-transfer example?
Changes to tracked objects in the same session, like sender.balance and receiver.balance, stay pending until one db.commit() writes them together. db.rollback() in an except block discards every pending change if anything fails first. That mirrors BEGIN/COMMIT/ROLLBACK without writing the SQL.
Why is a fresh Session created per request via Depends(get_db), rather than one shared session reused across the whole app's lifetime?
A long-lived shared session collects every object it has loaded or changed in its identity map, can leak state between unrelated requests, and isn't safe to use from several requests at once. A fresh session per request keeps each request's work isolated.
What does `uvicorn main:app --reload` mean, piece by piece?
uvicorn is the ASGI server running the app. main:app tells it to import the app object from the main module. --reload watches source files and restarts the server on changes; it's for development only, not production.
Why does splitting a FastAPI project into database.py, models.py, schemas.py, and router files mirror the layered structure of a typical Node backend?
Each file isolates one concern, like a Node app's routes/controllers/services/models split. database.py matches a db config module, models.py matches ORM model files, schemas.py plays the role of validation schemas, and routers match Express route files.
What's the risk of returning a raw SQLAlchemy model instance directly from a route with no response_model declared at all?
FastAPI would try to serialize the ORM object's attributes to JSON, possibly exposing every column, including ones never meant for clients, like a password_hash or internal audit fields. No schema limits what goes out.
Why does the delete_item example return `{"deleted": item_id}` rather than a 204 No Content response?
A JSON body confirming which id was deleted gives the caller explicit confirmation, which can be handier than a body-less 204. Either is fine. What matters is picking one convention for delete endpoints and sticking to it.