Create simple FastAPI application with SQLite and Alembic
- Set up project structure - Create FastAPI app with health endpoint - Implement SQLAlchemy with SQLite database - Set up Alembic for database migrations - Create CRUD operations for items - Add comprehensive documentation
This commit is contained in:
parent
f79319738d
commit
852e0a32b1
99
README.md
99
README.md
@ -1,3 +1,98 @@
|
||||
# FastAPI Application
|
||||
# Simple FastAPI Application
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
This is a simple FastAPI application with SQLite database integration, built to demonstrate best practices for API development with FastAPI.
|
||||
|
||||
## Features
|
||||
|
||||
- RESTful API with FastAPI
|
||||
- SQLite database with SQLAlchemy ORM
|
||||
- Database migrations with Alembic
|
||||
- CRUD operations for items
|
||||
- Health check endpoint
|
||||
- OpenAPI documentation
|
||||
- Code linting with Ruff
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
├── app/
|
||||
│ ├── api/
|
||||
│ │ ├── endpoints/
|
||||
│ │ │ ├── health.py
|
||||
│ │ │ └── items.py
|
||||
│ ├── core/
|
||||
│ │ └── config.py
|
||||
│ ├── db/
|
||||
│ │ └── session.py
|
||||
│ ├── models/
|
||||
│ │ └── models.py
|
||||
│ ├── schemas/
|
||||
│ │ └── item.py
|
||||
│ └── storage/
|
||||
│ └── db/
|
||||
├── migrations/
|
||||
│ ├── versions/
|
||||
│ │ └── 47e3b63e1a20_create_items_table.py
|
||||
│ ├── env.py
|
||||
│ └── script.py.mako
|
||||
├── alembic.ini
|
||||
├── main.py
|
||||
├── README.md
|
||||
└── requirements.txt
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
1. Clone the repository
|
||||
2. Install dependencies:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
## Running the Application
|
||||
|
||||
Start the application with uvicorn:
|
||||
|
||||
```bash
|
||||
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
|
||||
```
|
||||
|
||||
## API Documentation
|
||||
|
||||
Once the application is running, you can access:
|
||||
|
||||
- Swagger UI: [http://localhost:8000/docs](http://localhost:8000/docs)
|
||||
- ReDoc: [http://localhost:8000/redoc](http://localhost:8000/redoc)
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Health Check
|
||||
|
||||
- `GET /health` - Check if the API and database are running
|
||||
|
||||
### Items
|
||||
|
||||
- `GET /api/v1/items` - Get all items
|
||||
- `GET /api/v1/items/{item_id}` - Get an item by ID
|
||||
- `POST /api/v1/items` - Create a new item
|
||||
- `PATCH /api/v1/items/{item_id}` - Update an item
|
||||
- `DELETE /api/v1/items/{item_id}` - Delete an item
|
||||
|
||||
## Database Migrations
|
||||
|
||||
Run migrations:
|
||||
|
||||
```bash
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
Create a new migration:
|
||||
|
||||
```bash
|
||||
alembic revision --autogenerate -m "description"
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
74
alembic.ini
Normal file
74
alembic.ini
Normal file
@ -0,0 +1,74 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = migrations
|
||||
|
||||
# template used to generate migration files
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# timezone to use when rendering the date
|
||||
# within the migration file as well as the filename.
|
||||
# string value is passed to dateutil.tz.gettz()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the
|
||||
# "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; this defaults
|
||||
# to migrations/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path
|
||||
# version_locations = %(here)s/bar %(here)s/bat migrations/versions
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# SQLite URL using absolute path
|
||||
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
1
app/api/endpoints/__init__.py
Normal file
1
app/api/endpoints/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Module init file
|
24
app/api/endpoints/health.py
Normal file
24
app/api/endpoints/health.py
Normal file
@ -0,0 +1,24 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from app.db.session import get_db
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health", summary="Health check endpoint")
|
||||
def health_check(db: Session = Depends(get_db)):
|
||||
"""
|
||||
Health check endpoint to verify that the API is running and can connect to the database.
|
||||
|
||||
Returns:
|
||||
dict: A JSON object with the status of the service and database connection
|
||||
"""
|
||||
db_status = "healthy"
|
||||
try:
|
||||
# Try to execute a simple query
|
||||
db.execute("SELECT 1")
|
||||
except Exception:
|
||||
db_status = "unhealthy"
|
||||
|
||||
return {"status": "ok", "database": db_status}
|
133
app/api/endpoints/items.py
Normal file
133
app/api/endpoints/items.py
Normal file
@ -0,0 +1,133 @@
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.session import get_db
|
||||
from app.models import models
|
||||
from app.schemas.item import Item, ItemCreate, ItemUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
|
||||
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Create a new item.
|
||||
|
||||
Args:
|
||||
item: The item data to create
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
The created item
|
||||
"""
|
||||
db_item = models.Item(**item.model_dump())
|
||||
db.add(db_item)
|
||||
db.commit()
|
||||
db.refresh(db_item)
|
||||
return db_item
|
||||
|
||||
|
||||
@router.get("/items/", response_model=List[Item])
|
||||
def read_items(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
name: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Retrieve items with optional filtering.
|
||||
|
||||
Args:
|
||||
skip: Number of items to skip
|
||||
limit: Maximum number of items to return
|
||||
name: Optional filter by item name
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
List of items
|
||||
"""
|
||||
query = db.query(models.Item)
|
||||
|
||||
if name:
|
||||
query = query.filter(models.Item.name.ilike(f"%{name}%"))
|
||||
|
||||
items = query.offset(skip).limit(limit).all()
|
||||
return items
|
||||
|
||||
|
||||
@router.get("/items/{item_id}", response_model=Item)
|
||||
def read_item(item_id: int, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Get item by ID.
|
||||
|
||||
Args:
|
||||
item_id: The ID of the item to retrieve
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
The requested item
|
||||
|
||||
Raises:
|
||||
HTTPException: If item is not found
|
||||
"""
|
||||
item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/items/{item_id}", response_model=Item)
|
||||
def update_item(item_id: int, item_update: ItemUpdate, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Update an item.
|
||||
|
||||
Args:
|
||||
item_id: The ID of the item to update
|
||||
item_update: The updated item data
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
The updated item
|
||||
|
||||
Raises:
|
||||
HTTPException: If item is not found
|
||||
"""
|
||||
db_item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
||||
if db_item is None:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
|
||||
# Update item attributes that are provided
|
||||
update_data = item_update.model_dump(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(db_item, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_item)
|
||||
return db_item
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None
|
||||
)
|
||||
def delete_item(item_id: int, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Delete an item.
|
||||
|
||||
Args:
|
||||
item_id: The ID of the item to delete
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
HTTPException: If item is not found
|
||||
"""
|
||||
db_item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
||||
if db_item is None:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
|
||||
db.delete(db_item)
|
||||
db.commit()
|
||||
return None
|
19
app/core/config.py
Normal file
19
app/core/config.py
Normal file
@ -0,0 +1,19 @@
|
||||
from typing import List
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
PROJECT_NAME: str = "Simple FastAPI Application"
|
||||
PROJECT_DESCRIPTION: str = "A simple FastAPI application with SQLite database"
|
||||
PROJECT_VERSION: str = "0.1.0"
|
||||
|
||||
API_V1_STR: str = "/api/v1"
|
||||
|
||||
# CORS settings
|
||||
ALLOWED_ORIGINS: List[str] = ["*"]
|
||||
|
||||
class Config:
|
||||
case_sensitive = True
|
||||
|
||||
|
||||
settings = Settings()
|
32
app/db/session.py
Normal file
32
app/db/session.py
Normal file
@ -0,0 +1,32 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from pathlib import Path
|
||||
|
||||
# Create the database directory if it doesn't exist
|
||||
DB_DIR = Path("/app") / "storage" / "db"
|
||||
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Database URL
|
||||
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||
|
||||
# Create SQLAlchemy engine
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL,
|
||||
connect_args={"check_same_thread": False}, # SQLite specific
|
||||
)
|
||||
|
||||
# Create a session factory
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# Create a Base class for model declaration
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
# Dependency for database session
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
1
app/models/__init__.py
Normal file
1
app/models/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Module init file
|
15
app/models/models.py
Normal file
15
app/models/models.py
Normal file
@ -0,0 +1,15 @@
|
||||
from sqlalchemy import Column, Integer, String, Boolean, DateTime
|
||||
from sqlalchemy.sql import func
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class Item(Base):
|
||||
__tablename__ = "items"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, index=True)
|
||||
description = Column(String)
|
||||
price = Column(Integer) # Price in cents
|
||||
is_active = Column(Boolean, default=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
1
app/schemas/__init__.py
Normal file
1
app/schemas/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Module init file
|
34
app/schemas/item.py
Normal file
34
app/schemas/item.py
Normal file
@ -0,0 +1,34 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ItemBase(BaseModel):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
price: int # Price in cents
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class ItemCreate(ItemBase):
|
||||
pass
|
||||
|
||||
|
||||
class ItemUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
price: Optional[int] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class ItemInDB(ItemBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class Item(ItemInDB):
|
||||
pass
|
36
main.py
Normal file
36
main.py
Normal file
@ -0,0 +1,36 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
import uvicorn
|
||||
|
||||
from app.api.endpoints import health, items
|
||||
from app.core.config import settings
|
||||
from app.db.session import engine
|
||||
from app.models import models
|
||||
|
||||
# Create database tables
|
||||
models.Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI(
|
||||
title=settings.PROJECT_NAME,
|
||||
description=settings.PROJECT_DESCRIPTION,
|
||||
version=settings.PROJECT_VERSION,
|
||||
openapi_url=f"{settings.API_V1_STR}/openapi.json",
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
)
|
||||
|
||||
# Set up CORS middleware
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.ALLOWED_ORIGINS,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Include routers
|
||||
app.include_router(health.router, tags=["health"])
|
||||
app.include_router(items.router, prefix=settings.API_V1_STR, tags=["items"])
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
69
migrations/env.py
Normal file
69
migrations/env.py
Normal file
@ -0,0 +1,69 @@
|
||||
import os
|
||||
import sys
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
# Add the project directory to the sys.path
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
# Import the SQLAlchemy models
|
||||
from app.db.session import Base
|
||||
|
||||
# This is the Alembic Config object
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# Set target metadata for autogenerate
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline():
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL and not an Engine,
|
||||
though an Engine is acceptable here as well.
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online():
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine and associate a
|
||||
connection with the context.
|
||||
"""
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
is_sqlite = connection.dialect.name == "sqlite"
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
render_as_batch=is_sqlite, # This is important for SQLite to handle migrations properly
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
24
migrations/script.py.mako
Normal file
24
migrations/script.py.mako
Normal file
@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
44
migrations/versions/47e3b63e1a20_create_items_table.py
Normal file
44
migrations/versions/47e3b63e1a20_create_items_table.py
Normal file
@ -0,0 +1,44 @@
|
||||
"""create items table
|
||||
|
||||
Revision ID: 47e3b63e1a20
|
||||
Revises:
|
||||
Create Date: 2023-10-12 10:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "47e3b63e1a20"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
"items",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("name", sa.String(), nullable=True),
|
||||
sa.Column("description", sa.String(), nullable=True),
|
||||
sa.Column("price", sa.Integer(), nullable=True),
|
||||
sa.Column("is_active", sa.Boolean(), nullable=True, default=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("(CURRENT_TIMESTAMP)"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(op.f("ix_items_id"), "items", ["id"], unique=False)
|
||||
op.create_index(op.f("ix_items_name"), "items", ["name"], unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index(op.f("ix_items_name"), table_name="items")
|
||||
op.drop_index(op.f("ix_items_id"), table_name="items")
|
||||
op.drop_table("items")
|
9
requirements.txt
Normal file
9
requirements.txt
Normal file
@ -0,0 +1,9 @@
|
||||
fastapi>=0.100.0
|
||||
uvicorn>=0.23.0
|
||||
sqlalchemy>=2.0.0
|
||||
alembic>=1.12.0
|
||||
pydantic>=2.4.0
|
||||
pydantic-settings>=2.0.0
|
||||
python-multipart>=0.0.6
|
||||
email-validator>=2.0.0
|
||||
ruff>=0.0.284
|
Loading…
x
Reference in New Issue
Block a user