Create REST API with FastAPI and SQLite

This commit is contained in:
Automated Action 2025-05-16 14:34:27 +00:00
parent 83cb1fb24a
commit a813887960
21 changed files with 594 additions and 2 deletions

127
README.md
View File

@ -1,3 +1,126 @@
# 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 for handling item resources.
## Features
- FastAPI-based REST API with automatic OpenAPI documentation
- SQLAlchemy ORM with SQLite database
- Alembic database migrations
- CRUD operations for item resources
- Health check endpoint
- Async-ready with uvicorn
## Project Structure
```
.
├── alembic.ini
├── app/
│ ├── api/
│ │ ├── api.py
│ │ └── endpoints/
│ │ └── items.py
│ ├── core/
│ │ ├── config.py
│ │ └── database.py
│ ├── models/
│ │ ├── base.py
│ │ └── item.py
│ └── schemas/
│ └── item.py
├── main.py
├── migrations/
│ ├── env.py
│ ├── README
│ ├── script.py.mako
│ └── versions/
│ └── 001_initial_migration.py
└── requirements.txt
```
## Prerequisites
- Python 3.8+
- virtualenv (recommended)
## Installation
1. Clone the repository:
```bash
git clone <repository-url>
cd <repository-directory>
```
2. Create and activate a virtual environment (optional but recommended):
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
3. Install dependencies:
```bash
pip install -r requirements.txt
```
4. Initialize the database:
```bash
alembic upgrade head
```
## Running the API
Start the API server with:
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000
## API Documentation
FastAPI automatically generates interactive API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
- **GET /health** - Health check endpoint
- **GET /api/v1/items/** - List all items
- **POST /api/v1/items/** - Create a new item
- **GET /api/v1/items/{item_id}** - Get a specific item
- **PUT /api/v1/items/{item_id}** - Update a specific item
- **DELETE /api/v1/items/{item_id}** - Delete a specific item
## Development
### Database Migrations
After modifying models, create a new migration:
```bash
alembic revision -m "description of changes"
```
Apply migrations:
```bash
alembic upgrade head
```
Revert migrations:
```bash
alembic downgrade -1 # Go back one migration
```
### Code Quality
Run linting with Ruff:
```bash
ruff check .
ruff check --fix . # Auto-fix issues
```

73
alembic.ini Normal file
View File

@ -0,0 +1,73 @@
# 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 alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat alembic/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
# 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

0
app/__init__.py Normal file
View File

0
app/api/__init__.py Normal file
View File

6
app/api/api.py Normal file
View File

@ -0,0 +1,6 @@
from fastapi import APIRouter
from app.api.endpoints import items
api_router = APIRouter()
api_router.include_router(items.router, prefix="/items", tags=["items"])

View File

View File

@ -0,0 +1,81 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.models.item import Item
from app.schemas.item import Item as ItemSchema
from app.schemas.item import ItemCreate, ItemUpdate
router = APIRouter()
@router.get("/", response_model=List[ItemSchema])
def read_items(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db)
):
"""Get a list of items."""
items = db.query(Item).offset(skip).limit(limit).all()
return items
@router.post("/", response_model=ItemSchema, status_code=status.HTTP_201_CREATED)
def create_item(
item_in: ItemCreate,
db: Session = Depends(get_db)
):
"""Create a new item."""
db_item = Item(
name=item_in.name,
description=item_in.description,
is_active=item_in.is_active
)
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@router.get("/{item_id}", response_model=ItemSchema)
def read_item(
item_id: str,
db: Session = Depends(get_db)
):
"""Get an 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("/{item_id}", response_model=ItemSchema)
def update_item(
item_id: str,
item_in: 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_in.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(db_item, field, value)
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_item(
item_id: str,
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

0
app/core/__init__.py Normal file
View File

27
app/core/config.py Normal file
View File

@ -0,0 +1,27 @@
from pathlib import Path
from typing import Any, Dict, Optional
from pydantic import BaseSettings, validator
class Settings(BaseSettings):
"""Application settings."""
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Generic REST API Service"
# Configure database
DB_DIR: Path = Path("/app") / "storage" / "db"
SQLALCHEMY_DATABASE_URL: str = ""
@validator("SQLALCHEMY_DATABASE_URL", pre=True)
def assemble_db_url(cls, v: Optional[str], values: Dict[str, Any]) -> str:
if v and len(v) > 0:
return v
# Ensure DB directory exists
db_dir = values.get("DB_DIR")
if db_dir:
Path(db_dir).mkdir(parents=True, exist_ok=True)
return f"sqlite:///{values.get('DB_DIR')}/db.sqlite"
settings = Settings()

26
app/core/database.py Normal file
View File

@ -0,0 +1,26 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Ensure DB directory exists
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Dependency to get DB session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1,3 @@
from app.models.item import Item
__all__ = ["Item"]

20
app/models/base.py Normal file
View File

@ -0,0 +1,20 @@
import uuid
from datetime import datetime
from sqlalchemy import Column, DateTime, String
from sqlalchemy.ext.declarative import declared_attr
from app.core.database import Base
class BaseModel(Base):
"""Base SQLAlchemy model with common fields."""
__abstract__ = True
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
id = Column(String(36), primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

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

@ -0,0 +1,9 @@
from sqlalchemy import Column, String, Text, Boolean
from app.models.base import BaseModel
class Item(BaseModel):
"""Item model."""
name = Column(String(100), index=True, nullable=False)
description = Column(Text, nullable=True)
is_active = Column(Boolean, default=True)

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

@ -0,0 +1,3 @@
from app.schemas.item import Item, ItemCreate, ItemUpdate
__all__ = ["Item", "ItemCreate", "ItemUpdate"]

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

@ -0,0 +1,32 @@
from typing import Optional
from datetime import datetime
from pydantic import BaseModel
class ItemBase(BaseModel):
"""Base schema for Item."""
name: str
description: Optional[str] = None
is_active: bool = True
class ItemCreate(ItemBase):
"""Schema for creating an Item."""
pass
class ItemUpdate(BaseModel):
"""Schema for updating an Item."""
name: Optional[str] = None
description: Optional[str] = None
is_active: Optional[bool] = None
class ItemInDBBase(ItemBase):
"""Base schema for Item with DB fields."""
id: str
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True
class Item(ItemInDBBase):
"""Schema for returning an Item."""
pass

34
main.py Normal file
View File

@ -0,0 +1,34 @@
import uvicorn
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from app.core.config import settings
from app.core.database import get_db
from app.api.api import api_router
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json"
)
# Include routers
app.include_router(api_router, prefix=settings.API_V1_STR)
# Health check endpoint
@app.get("/health", tags=["health"])
async def health(db: Session = Depends(get_db)):
"""Health check endpoint that verifies API and database connectivity."""
try:
# Verify the database connection
db.execute("SELECT 1")
db_status = "ok"
except Exception as e:
db_status = f"error: {str(e)}"
return {
"status": "ok",
"database": db_status,
"api_version": "1.0.0"
}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

6
migrations/README Normal file
View File

@ -0,0 +1,6 @@
Generic single-database configuration with an SQLite database.
To run migrations:
1. Update models in app/models/
2. Run manual migration script generation (autogenerate is disabled)
3. Apply migrations with `alembic upgrade head`

81
migrations/env.py Normal file
View File

@ -0,0 +1,81 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from app.core.database import Base
# 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 myapp import mymodel
# target_metadata = mymodel.Base.metadata
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:
is_sqlite = connection.dialect.name == 'sqlite'
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=is_sqlite, # Key configuration for SQLite
)
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,37 @@
"""Initial migration
Revision ID: 001
Revises:
Create Date: 2023-10-22
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# Create item table
op.create_table(
'item',
sa.Column('id', sa.String(36), primary_key=True, index=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('name', sa.String(100), index=True, nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('is_active', sa.Boolean(), default=True),
)
op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False)
op.create_index(op.f('ix_item_name'), 'item', ['name'], unique=False)
def downgrade():
op.drop_index(op.f('ix_item_name'), table_name='item')
op.drop_index(op.f('ix_item_id'), table_name='item')
op.drop_table('item')

7
requirements.txt Normal file
View File

@ -0,0 +1,7 @@
fastapi>=0.104.0
uvicorn>=0.24.0
sqlalchemy>=2.0.0
pydantic>=2.4.0
alembic>=1.12.0
python-dotenv>=1.0.0
ruff>=0.1.0