YouTip LogoYouTip

Fastapi Blog Sqlalchemy

In this chapter, you will learn how to define data models using native SQLAlchemy ORM and manage database sessions through FastAPI dependency injection. * * * ## Why Doesn't FastAPI Use a Built-in ORM? Django has a built-in ORM, Flask recommends Flask-SQLAlchemy. FastAPI doesn't have a built-in ORM β€” it wants you to choose the most suitable tool. SQLAlchemy + Pydantic is the community-recognized best combination. (venv) $ pip install sqlalchemy * * * ## Configure Database Connection ## Example # File path: database.py from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, DeclarativeBase # SQLite database file path SQLALCHEMY_DATABASE_URL ="sqlite:///./blog.db" # Create engine: check_same_thread is a special parameter for SQLite engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}# SQLite specific: allow cross-thread usage ) # Create session factory SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) # Base class: all ORM models inherit from it class Base(DeclarativeBase): pass > `check_same_thread=False` is a necessary configuration for SQLite in FastAPI. By default, SQLite doesn't allow the same connection to be used across threads, but in Web applications each request may be handled in different threads. ### Dependency Injection: get_db ## Example # File path: database.py (append) from fastapi import Depends def get_db(): """FastAPI dependency injection: create an independent database session for each request""" db = SessionLocal() try: yield db # Use this session during the request finally: db.close()# Automatically close the session after the request ends to prevent connection leaks `Depends(get_db)` is FastAPI's dependency injection system. Route functions automatically receive database sessions through dependency injection. * * * ## Define Models: Post and Category ## Example # File path: models.py from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey from sqlalchemy.orm import relationship from datetime import datetime from database import Base class Category(Base): """Article category""" __tablename__ ="categories" id= Column(Integer, primary_key=True, index=True) name = Column(String(50), unique=True, nullable=False) slug = Column(String(50), unique=True, nullable=False) # back_populates for bidirectional relationship posts = relationship("Post", back_populates="category") class Post(Base): """Blog post""" __tablename__ ="posts" id= Column(Integer, primary_key=True, index=True) title = Column(String(200), nullable=False) slug = Column(String(200), unique=True, nullable=False) summary = Column(Text, default="") content = Column(Text, nullable=False) category_id = Column(Integer, ForeignKey("categories.id"), nullable=False) created_at = Column(DateTime, default=datetime.utcnow) updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) # Bidirectional relationship with Category category = relationship("Category", back_populates="posts" > FastAPI uses native SQLAlchemy (not Flask-SQLAlchemy's `db.Model`). Note the differences in Column import, Base inheritance, and relationshipway of writing. There will be a comparison table later. * * * ## Initialize Database Tables ## Example # File path: main.py create tables in startup event from fastapi import FastAPI from database import engine, Base from models import Category, Post # Make sure model classes are imported so Base.metadata can recognize them app = FastAPI() @app.on_event("startup") def on_startup(): """Automatically create database tables when application starts (only for development)""" Base.metadata.create_all(bind=engine) Later we will switch to Alembic migrations (Chapter 6). `create_all` is only used during the rapid prototyping phase. * * * ## Insert Test Data Insert test data in a Python script: ## Example # File path: seed.py (run once only) from database import SessionLocal from models import Category, Post db = SessionLocal() # Create categories py = Category(name="Python", slug="python") css = Category(name="CSS", slug="css") fastapi = Category(name="FastAPI", slug="fastapi") db.add_all([py, css, fastapi]) db.commit() # Create posts db.add_all([ Post(title="FastAPI Getting StartedComplete Guide", slug="fastapi-guide", summary="Learn FastAPI from Scratch", content="

Why Choose FastAPI?

...

", category_id=fastapi.id), Post(title="Python Coroutine Detailed Explanation", slug="python-coroutine", summary="Understand asyncio", content="

What is a Coroutine?

...

", category_id=py.id), Post(title="CSS Grid Layout in Practice", slug="css-grid", summary="Implement Responsive Layouts with Grid", content="

Grid Getting Started

...

", category_id=css.id), ]) db.commit() db.close() print("Test Data Insertion Completed!") Run `python seed.py`, and 3 articles will be inserted into the database. * * * ## Four Framework ORM Syntax Comparison | Operation | Django | Flask-SQLAlchemy | FastAPI (Native SQLAlchemy) | | --- | --- | --- | --- | | Base class | models.Model | db.Model | Base (DeclarativeBase) | | Field | models.CharField() | db.Column(...) | Column(...) | | Foreign key | ForeignKey(to, on_delete) | db.ForeignKey('table.col') | ForeignKey('table.col') | | Relationship | Auto reverse | db.relationship + backref | relationship + back_populates | | Session | Auto managed | db.session | Session
← Fastapi Blog Routers ViewsFastapi Blog Project Init β†’