0PricingLogin
FastAPI Backend Development Bootcamp · Lesson

CRUD Operations with SQLAlchemy

Implement Create, Read, Update, and Delete operations for your API endpoints using SQLAlchemy ORM.

CRUD Operations: The Core

Welcome to Lesson 3! Today, we'll master CRUD operations using FastAPI and SQLAlchemy. CRUD stands for:

  • Create: Adding new data.
  • Read: Retrieving existing data.
  • Update: Modifying existing data.
  • Delete: Removing data.

These four operations are the foundation of almost any application that interacts with a database.

Setup: Models & Session

Before diving into CRUD, let's set up our SQLAlchemy model and Pydantic schemas. We'll use an in-memory SQLite database for our runnable examples.

First, our SQLAlchemy Todo model to represent a task:

from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Todo(Base):
    __tablename__ = "todos"
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    description = Column(String, default="")
    completed = Column(Boolean, default=False)

And Pydantic schemas for request/response:

from pydantic import BaseModel

class TodoCreate(BaseModel):
    title: str
    description: str = ""
    completed: bool = False

class TodoResponse(TodoCreate):
    id: int

    class Config:
        orm_mode = True

All lessons in this course

  1. SQLAlchemy ORM Fundamentals
  2. Connecting FastAPI to PostgreSQL
  3. CRUD Operations with SQLAlchemy
  4. Database Migrations with Alembic
← Back to FastAPI Backend Development Bootcamp