Create FastAPI REST API with SQLite

Features:
- Project structure setup
- Database configuration with SQLAlchemy
- Item model and CRUD operations
- API endpoints for items
- Alembic migrations
- Health check endpoint
- Comprehensive documentation

generated with BackendIM... (backend.im)
This commit is contained in:
Automated Action 2025-05-14 00:49:31 +00:00
parent 9707ef70cd
commit 1349113fe0
17 changed files with 505 additions and 2 deletions

View File

@ -1,3 +1,67 @@
# FastAPI Application # Generic REST API Service
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A modern REST API service built with FastAPI and SQLite, providing a clean architecture and RESTful endpoints.
## Features
- Fast and efficient API with FastAPI
- SQLite database with SQLAlchemy ORM
- Database migrations with Alembic
- Pydantic schemas for validation
- Health check endpoint
- Full CRUD operations for items
- OpenAPI documentation
## Project Structure
```
.
├── app # Application package
│ ├── database.py # Database configuration
│ ├── models # SQLAlchemy models
│ ├── routes # API routes and endpoints
│ └── schemas # Pydantic schemas
├── migrations # Alembic migrations
├── alembic.ini # Alembic configuration
├── main.py # Application entry point
└── requirements.txt # Project dependencies
```
## API Endpoints
- `GET /health` - Health check endpoint
- `GET /api/v1/items` - List all items
- `GET /api/v1/items/{item_id}` - Get a specific item
- `POST /api/v1/items` - Create a new item
- `PUT /api/v1/items/{item_id}` - Update an item
- `DELETE /api/v1/items/{item_id}` - Delete an item
## API Documentation
Once the application is running, you can access the API documentation:
- Swagger UI - `/docs`
- ReDoc - `/redoc`
## Development
### Requirements
- Python 3.8+
- SQLite
### Setup
1. Install dependencies:
```bash
pip install -r requirements.txt
```
2. Run the application:
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000.

84
alembic.ini Normal file
View File

@ -0,0 +1,84 @@
# 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
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks=black
# black.type=console_scripts
# black.entrypoint=black
# black.options=-l 79
# 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/__init__.py Normal file
View File

@ -0,0 +1 @@
# app package

31
app/database.py Normal file
View File

@ -0,0 +1,31 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pathlib import Path
# Create directory for database
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
# SQLite database URL
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
# Create engine
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
# Create session
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Create base model class
Base = declarative_base()
# Dependency for database sessions
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

4
app/models/__init__.py Normal file
View File

@ -0,0 +1,4 @@
from app.models.item import Item
# Add all models here
__all__ = ["Item"]

14
app/models/item.py Normal file
View File

@ -0,0 +1,14 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text
from sqlalchemy.sql import func
from app.database import Base
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(100), nullable=False)
description = Column(Text, nullable=True)
price = Column(Integer, nullable=False) # 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())

3
app/routes/__init__.py Normal file
View File

@ -0,0 +1,3 @@
from app.routes import health, api
__all__ = ["health", "api"]

72
app/routes/api.py Normal file
View File

@ -0,0 +1,72 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from app.database import get_db
from app.models.item import Item
from app.schemas.item import ItemCreate, ItemUpdate, ItemResponse
router = APIRouter(tags=["Items"])
@router.post("/items", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
"""
Create a new item.
"""
db_item = Item(
name=item.name,
description=item.description,
price=item.price,
is_active=item.is_active
)
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@router.get("/items", response_model=List[ItemResponse])
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
"""
Retrieve items.
"""
items = db.query(Item).offset(skip).limit(limit).all()
return items
@router.get("/items/{item_id}", response_model=ItemResponse)
def read_item(item_id: int, db: Session = Depends(get_db)):
"""
Get a specific item by ID.
"""
db_item = db.query(Item).filter(Item.id == item_id).first()
if db_item is None:
raise HTTPException(status_code=404, detail="Item not found")
return db_item
@router.put("/items/{item_id}", response_model=ItemResponse)
def update_item(item_id: int, item: ItemUpdate, db: Session = Depends(get_db)):
"""
Update an item.
"""
db_item = db.query(Item).filter(Item.id == item_id).first()
if db_item is None:
raise HTTPException(status_code=404, detail="Item not found")
update_data = item.dict(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)
def delete_item(item_id: int, db: Session = Depends(get_db)):
"""
Delete an item.
"""
db_item = db.query(Item).filter(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

24
app/routes/health.py Normal file
View File

@ -0,0 +1,24 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.database import get_db
router = APIRouter(tags=["Health"])
@router.get("/health", summary="Health check endpoint")
def health_check(db: Session = Depends(get_db)):
"""
Health check endpoint that returns the status of the API and database connection.
"""
health_status = {
"status": "healthy",
"database": "connected"
}
try:
# Test database connection
db.execute("SELECT 1")
except Exception:
health_status["database"] = "disconnected"
health_status["status"] = "unhealthy"
return health_status

4
app/schemas/__init__.py Normal file
View File

@ -0,0 +1,4 @@
from app.schemas.item import ItemBase, ItemCreate, ItemUpdate, ItemInDB, ItemResponse
# Add all schemas here
__all__ = ["ItemBase", "ItemCreate", "ItemUpdate", "ItemInDB", "ItemResponse"]

30
app/schemas/item.py Normal file
View File

@ -0,0 +1,30 @@
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
class ItemBase(BaseModel):
name: str = Field(..., min_length=1, max_length=100, example="Example Item")
description: Optional[str] = Field(None, example="This is an example item description")
price: int = Field(..., gt=0, example=1999) # Price in cents (e.g., 19.99 USD = 1999)
is_active: bool = Field(True, example=True)
class ItemCreate(ItemBase):
pass
class ItemUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=100, example="Updated Item")
description: Optional[str] = Field(None, example="This is an updated description")
price: Optional[int] = Field(None, gt=0, example=2499)
is_active: Optional[bool] = Field(None, example=True)
class ItemInDB(ItemBase):
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True
class ItemResponse(ItemInDB):
"""Response model for items"""
pass

30
main.py Normal file
View File

@ -0,0 +1,30 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pathlib import Path
from app.routes import health, api
from app.database import engine, Base
# Create database tables
Base.metadata.create_all(bind=engine)
app = FastAPI(title="Generic REST API Service",
description="A generic REST API service built with FastAPI and SQLite",
version="0.1.0")
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(health.router)
app.include_router(api.router, prefix="/api/v1")
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

1
migrations/__init__.py Normal file
View File

@ -0,0 +1 @@
# migrations package

75
migrations/env.py Normal file
View File

@ -0,0 +1,75 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from pathlib import Path
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
from app.database import Base
import app.models # Import all models
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
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. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
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:
context.configure(
connection=connection, target_metadata=target_metadata
)
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
View 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"}

View File

@ -0,0 +1,36 @@
"""Initial migration
Revision ID: 2fbbf2d05a82
Revises:
Create Date: 2025-05-14 12:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2fbbf2d05a82'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# Create items table
op.create_table('items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('price', sa.Integer(), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False, server_default=sa.text('1')),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)')),
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)
def downgrade():
op.drop_index(op.f('ix_items_id'), table_name='items')
op.drop_table('items')

6
requirements.txt Normal file
View File

@ -0,0 +1,6 @@
fastapi==0.104.1
uvicorn==0.24.0
sqlalchemy==2.0.23
pydantic==2.4.2
alembic==1.12.1
ruff==0.1.5