3 Hours

13. PostgreSQL Integration

Database

PostgreSQL is a powerful, open-source relational database system. It is the recommended production database for FastAPI applications due to its reliability, performance, and advanced features like JSON support and full-text search. To test these examples, install PostgreSQL locally or use Docker.

Installing PostgreSQL with Docker

For development, you can run PostgreSQL using Docker, which ensures a consistent environment.

Bash
# Run PostgreSQL with Docker
docker run --name postgres-dev \
  -e POSTGRES_USER=fastapi \
  -e POSTGRES_PASSWORD=secret \
  -e POSTGRES_DB=myapp \
  -p 5432:5432 \
  -d postgres:15

# Alternative: Install locally
# Ubuntu: sudo apt install postgresql
# Mac: brew install postgresql

Connection Configuration

Store database connection settings in your config file and load them from environment variables.

Python 3
# app/config.py
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    POSTGRES_USER: str = "postgres"
    POSTGRES_PASSWORD: str = ""
    POSTGRES_HOST: str = "localhost"
    POSTGRES_PORT: int = 5432
    POSTGRES_DB: str = "myapp"

    @property
    def DATABASE_URL(self) -> str:
        return f"postgresql://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}@{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DB}"

    @property
    def ASYNC_DATABASE_URL(self) -> str:
        return f"postgresql+asyncpg://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}@{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DB}"

settings = Settings()

Async Database Setup

Configure async database engine for better performance under high concurrency.

Python 3
# app/database.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, declarative_base
from app.config import settings

engine = create_async_engine(
    settings.ASYNC_DATABASE_URL,
    echo=settings.DEBUG,
    future=True,
    pool_size=20,
    max_overflow=10
)

AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

Base = declarative_base()

async def get_db() -> AsyncSession:
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()

CRUD Operations with Async SQLAlchemy

Perform database operations using async/await syntax.

Python 3
# app/crud/user.py
from sqlalchemy import select, update, delete
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.user import User
from app.schemas.user import UserCreate

async def get_user(db: AsyncSession, user_id: int):
    result = await db.execute(select(User).where(User.id == user_id))
    return result.scalar_one_or_none()

async def get_user_by_email(db: AsyncSession, email: str):
    result = await db.execute(select(User).where(User.email == email))
    return result.scalar_one_or_none()

async def get_users(db: AsyncSession, skip: int = 0, limit: int = 100):
    result = await db.execute(select(User).offset(skip).limit(limit))
    return result.scalars().all()

async def create_user(db: AsyncSession, user: UserCreate):
    db_user = User(
        email=user.email,
        username=user.username,
        hashed_password=user.password
    )
    db.add(db_user)
    await db.commit()
    await db.refresh(db_user)
    return db_user

async def update_user(db: AsyncSession, user_id: int, user_data: dict):
    await db.execute(update(User).where(User.id == user_id).values(**user_data))
    await db.commit()
    return await get_user(db, user_id)

async def delete_user(db: AsyncSession, user_id: int):
    result = await db.execute(delete(User).where(User.id == user_id))
    await db.commit()
    return result.rowcount > 0

PostgreSQL Specific Features

PostgreSQL offers advanced data types that SQLAlchemy supports.

Python 3
from sqlalchemy import Column, Integer, String, JSON, ARRAY
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
import uuid

class Product(Base):
    __tablename__ = "products"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    name = Column(String, nullable=False)
    metadata = Column(JSON, default=dict)
    tags = Column(ARRAY(String), default=list)
    search_vector = Column(TSVECTOR)

# JSON field operations
product.metadata = {"color": "red", "size": "large"}

# Array operations
product.tags = ["electronics", "wireless"]

# Query JSON field
stmt = select(Product).where(Product.metadata["color"].astext == "red")

Connection Pooling

Proper connection pooling is critical for production performance.

Python 3
engine = create_async_engine(
    settings.ASYNC_DATABASE_URL,
    pool_size=20,
    max_overflow=10,
    pool_pre_ping=True,
    pool_recycle=3600,
    echo=False
)
Local Setup: Create a .env file with your PostgreSQL credentials. Never commit .env to version control.

Knowledge Check

Ready to test your understanding of 13. PostgreSQL Integration?

Back