This project demonstrates how to connect a FastAPI backend to a relational database using the SQLAlchemy ORM and how to manage database schema changes using Alembic. While the code is configured to use PostgreSQL (via psycopg2), it falls back to SQLite for easy local testing if no Postgres server is running. It includes a unified HTML/JS frontend interface to manage "Items" in the database.
61-fastapi-postgres/
main.py # FastAPI application and routes
database.py # SQLAlchemy engine and session management
models.py # SQLAlchemy database models
schemas.py # Pydantic data validation schemas
crud.py # CRUD operations separating DB logic from routes
index.html # Unified single-file Frontend (HTML/CSS/JS)
alembic.ini # Alembic configuration file
alembic/ # Alembic migration scripts directory
requirements.txt # Dependencies
README.md # This file
pip install -r requirements.txtInstead of relying on Base.metadata.create_all(), we use Alembic to create the tables:
alembic upgrade headuvicorn main:app --reloadOpen index.html directly in your browser or run a simple server:
python -m http.server 5500Then navigate to http://127.0.0.1:5500.
[
{
"id": 1,
"title": "Smartphone",
"description": "Latest model",
"is_active": true
}
]- SQLAlchemy ORM: Mapping Python classes to database tables.
- Dependency Injection: Injecting a database session
SessionLocalinto route handlers. - Alembic: Managing schema changes over time via tracked migration scripts.
- Pydantic Schemas: Differentiating between generic schemas (Create/Update) and ORM-enabled schemas (Response).
- Unified Frontend: Using a single-file
index.htmlwith inline<style>and<script>containing modern styling and API fetch logic.