Create REST API service with FastAPI and SQLite

- Set up project structure with app modules
- Configure SQLite database connection
- Set up Alembic for database migrations
- Implement Item model with CRUD operations
- Create API endpoints for items management
- Add health check endpoint
- Add API documentation
- Add comprehensive README
This commit is contained in:
Automated Action 2025-05-19 15:58:21 +00:00
parent 37b72adce6
commit 993e1df71e
30 changed files with 957 additions and 2 deletions

139
README.md
View File

@ -1,3 +1,138 @@
# FastAPI Application
# REST API Service
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A modern, lightweight REST API service built with FastAPI and SQLite.
## Features
- **FastAPI Framework**: High performance, easy to learn, fast to code
- **SQLite Database**: Simple, reliable, and zero-configuration database
- **Alembic Migrations**: Database versioning and migration management
- **Pydantic Models**: Data validation and schema definition
- **API Documentation**: Interactive OpenAPI docs with Swagger and ReDoc
- **Health Check Endpoint**: Monitoring and service status reporting
- **CRUD Operations**: Complete Create, Read, Update, Delete functionality
- **SQLAlchemy ORM**: Object-Relational Mapping for database interactions
## Getting Started
### Prerequisites
- Python 3.8 or newer
- pip (Python package installer)
### Installation
1. Clone the repository:
```bash
git clone <repository-url>
cd <repository-directory>
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Initialize the database:
```bash
alembic upgrade head
```
4. Start the server:
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000
## API Documentation
Once the server is running, you can access:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
### Health Check
- `GET /api/v1/health`: Check the service health status
### Items
- `GET /api/v1/items`: List all items
- `POST /api/v1/items`: Create a new item
- `GET /api/v1/items/{id}`: Get a specific item
- `PUT /api/v1/items/{id}`: Update a specific item
- `DELETE /api/v1/items/{id}`: Delete a specific item
## Project Structure
```
.
├── alembic.ini # Alembic configuration
├── app # Application package
│ ├── api # API endpoints
│ │ ├── deps.py # Dependencies for API endpoints
│ │ ├── endpoints # Endpoint implementation
│ │ │ ├── health.py # Health check endpoint
│ │ │ └── items.py # Item endpoints
│ │ └── routes.py # API router
│ ├── core # Core functionality
│ │ └── config.py # Application configuration
│ ├── db # Database
│ │ ├── base.py # Base model imports for Alembic
│ │ ├── base_class.py # Base class for database models
│ │ └── session.py # Database session
│ ├── models # Database models
│ │ └── item.py # Item model
│ ├── schemas # Pydantic schemas
│ │ ├── health.py # Health check schemas
│ │ └── item.py # Item schemas
│ └── services # Business logic
│ └── crud # CRUD operations
│ ├── base.py # Base CRUD class
│ └── item.py # Item CRUD operations
├── main.py # Application entry point
├── migrations # Alembic migrations
│ ├── env.py # Alembic environment
│ ├── README # Alembic README
│ ├── script.py.mako # Alembic script template
│ └── versions # Migration versions
│ └── 20231230_000000_create_items_table.py # Initial migration
└── requirements.txt # Dependencies
```
## Development
### Linting
This project uses Ruff for linting:
```bash
ruff check .
```
To automatically fix issues:
```bash
ruff check --fix .
```
### Database Migrations
To create a new migration:
```bash
alembic revision --autogenerate -m "Description of changes"
```
To apply migrations:
```bash
alembic upgrade head
```
## License
This project is licensed under the MIT License - see the LICENSE file for details.

85
alembic.ini Normal file
View File

@ -0,0 +1,85 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration files
file_template = %%(year)d%%(month).2d%%(day).2d_%%(hour).2d%%(minute).2d%%(second).2d_%%(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 example
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 @@
# Empty init file to make directory a package

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

@ -0,0 +1 @@
# Empty init file to make directory a package

20
app/api/deps.py Normal file
View File

@ -0,0 +1,20 @@
"""
API dependencies.
"""
from typing import Generator
from app.db.session import SessionLocal
def get_db() -> Generator:
"""
Get database session.
Yields:
Session: Database session
"""
db = SessionLocal()
try:
yield db
finally:
db.close()

View File

@ -0,0 +1 @@
# Empty init file to make directory a package

View File

@ -0,0 +1,27 @@
"""
API endpoints for health checks.
"""
from typing import Any
from fastapi import APIRouter
from app.schemas.health import HealthCheck, HealthStatus
router = APIRouter()
# Get the version from the package
VERSION = "0.1.0"
@router.get("/", response_model=HealthCheck)
def health_check() -> Any:
"""
Health check endpoint.
Returns:
Health status
"""
return {
"status": HealthStatus.OK,
"version": VERSION,
}

140
app/api/endpoints/items.py Normal file
View File

@ -0,0 +1,140 @@
"""
API endpoints for items.
"""
from typing import List, Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api.deps import get_db
from app.schemas.item import Item as ItemSchema
from app.schemas.item import ItemCreate, ItemUpdate
from app.services.crud import item
router = APIRouter()
@router.get("/", response_model=List[ItemSchema])
def read_items(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
active_only: bool = False,
) -> Any:
"""
Retrieve items.
Args:
db: Database session
skip: Number of items to skip
limit: Maximum number of items to return
active_only: Only return active items
Returns:
List of items
"""
if active_only:
items = item.get_multi_by_active(db, skip=skip, limit=limit)
else:
items = item.get_multi(db, skip=skip, limit=limit)
return items
@router.post("/", response_model=ItemSchema, status_code=status.HTTP_201_CREATED)
def create_item(
*,
db: Session = Depends(get_db),
item_in: ItemCreate,
) -> Any:
"""
Create new item.
Args:
db: Database session
item_in: Item to create
Returns:
Created item
"""
db_item = item.get_by_title(db, title=item_in.title)
if db_item:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Item with this title already exists",
)
return item.create(db, obj_in=item_in)
@router.get("/{id}", response_model=ItemSchema)
def read_item(
*,
db: Session = Depends(get_db),
id: int,
) -> Any:
"""
Get item by ID.
Args:
db: Database session
id: Item ID
Returns:
Item
"""
db_item = item.get(db, id=id)
if not db_item:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found",
)
return db_item
@router.put("/{id}", response_model=ItemSchema)
def update_item(
*,
db: Session = Depends(get_db),
id: int,
item_in: ItemUpdate,
) -> Any:
"""
Update an item.
Args:
db: Database session
id: Item ID
item_in: Item data to update
Returns:
Updated item
"""
db_item = item.get(db, id=id)
if not db_item:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found",
)
return item.update(db, db_obj=db_item, obj_in=item_in)
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_item(
*,
db: Session = Depends(get_db),
id: int,
) -> None:
"""
Delete an item.
Args:
db: Database session
id: Item ID
"""
db_item = item.get(db, id=id)
if not db_item:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found",
)
item.remove(db, id=id)
return None

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

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

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

@ -0,0 +1 @@
# Empty init file to make directory a package

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

@ -0,0 +1,18 @@
"""
Configuration settings for the REST API Service.
"""
from pathlib import Path
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
"""Application settings"""
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "REST API Service"
# Database
DB_DIR: Path = Path("/app/storage/db")
DB_FILENAME: str = "db.sqlite"
settings = Settings()

1
app/db/__init__.py Normal file
View File

@ -0,0 +1 @@
# Empty init file to make directory a package

6
app/db/base.py Normal file
View File

@ -0,0 +1,6 @@
"""
Import all models to ensure they are registered with SQLAlchemy Base.
"""
# Import all models here for Alembic to detect
from app.db.base_class import Base # noqa
from app.models.item import Item # noqa

18
app/db/base_class.py Normal file
View File

@ -0,0 +1,18 @@
"""
Base class for database models.
"""
from typing import Any
from sqlalchemy.ext.declarative import as_declarative, declared_attr
@as_declarative()
class Base:
"""Base class for all database models."""
id: Any
__name__: str
@declared_attr
def __tablename__(cls) -> str:
"""Generate database table name automatically from the class name."""
return cls.__name__.lower()

36
app/db/session.py Normal file
View File

@ -0,0 +1,36 @@
"""
Database session setup.
"""
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Database directory
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
# Create engine
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False} # Required for SQLite
)
# Create session
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
"""
Dependency function to get a database session.
Yields:
Session: Database session
"""
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1 @@
# Empty init file to make directory a package

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

@ -0,0 +1,17 @@
"""
Database model for items.
"""
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.sql import func
from app.db.base_class import Base
class Item(Base):
"""Item model for storing item data."""
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String)
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())

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

@ -0,0 +1,5 @@
"""
Schemas package.
"""
from .health import HealthCheck, HealthStatus # noqa: F401
from .item import Item, ItemCreate, ItemUpdate, ItemInDB # noqa: F401

18
app/schemas/health.py Normal file
View File

@ -0,0 +1,18 @@
"""
Pydantic schemas for health checks.
"""
from enum import Enum
from pydantic import BaseModel
class HealthStatus(str, Enum):
"""Enum for health status."""
OK = "ok"
ERROR = "error"
class HealthCheck(BaseModel):
"""Schema for health check response."""
status: HealthStatus
version: str

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

@ -0,0 +1,47 @@
"""
Pydantic schemas for Item.
"""
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
class ItemBase(BaseModel):
"""Base schema for Item."""
title: str
description: Optional[str] = None
is_active: bool = True
class ItemCreate(ItemBase):
"""Schema for creating a new Item."""
pass
class ItemUpdate(BaseModel):
"""Schema for updating an existing Item."""
title: Optional[str] = None
description: Optional[str] = None
is_active: Optional[bool] = None
class ItemInDBBase(ItemBase):
"""Base schema for Item in DB."""
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
"""Pydantic config."""
from_attributes = True
class Item(ItemInDBBase):
"""Schema for Item used in response."""
pass
class ItemInDB(ItemInDBBase):
"""Schema for Item stored in DB."""
pass

1
app/services/__init__.py Normal file
View File

@ -0,0 +1 @@
# Empty init file to make directory a package

View File

@ -0,0 +1,4 @@
"""
CRUD operations package.
"""
from .item import item # noqa: F401

121
app/services/crud/base.py Normal file
View File

@ -0,0 +1,121 @@
"""
Base CRUD operations.
"""
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.db.base_class import Base
ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
"""Base class for CRUD operations."""
def __init__(self, model: Type[ModelType]):
"""
Initialize with SQLAlchemy model class.
Args:
model: SQLAlchemy model class
"""
self.model = model
def get(self, db: Session, id: Any) -> Optional[ModelType]:
"""
Get an object by ID.
Args:
db: Database session
id: Object ID
Returns:
Optional object
"""
return db.query(self.model).filter(self.model.id == id).first()
def get_multi(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[ModelType]:
"""
Get multiple objects.
Args:
db: Database session
skip: Number of objects to skip
limit: Maximum number of objects to return
Returns:
List of objects
"""
return db.query(self.model).offset(skip).limit(limit).all()
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
"""
Create a new object.
Args:
db: Database session
obj_in: Object to create
Returns:
Created object
"""
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data) # type: ignore
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
self,
db: Session,
*,
db_obj: ModelType,
obj_in: Union[UpdateSchemaType, Dict[str, Any]]
) -> ModelType:
"""
Update an object.
Args:
db: Database session
db_obj: Object to update
obj_in: Object data to update with
Returns:
Updated object
"""
obj_data = jsonable_encoder(db_obj)
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.model_dump(exclude_unset=True)
for field in obj_data:
if field in update_data:
setattr(db_obj, field, update_data[field])
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def remove(self, db: Session, *, id: Any) -> ModelType:
"""
Delete an object.
Args:
db: Database session
id: Object ID
Returns:
Deleted object
"""
obj = db.query(self.model).get(id)
db.delete(obj)
db.commit()
return obj

52
app/services/crud/item.py Normal file
View File

@ -0,0 +1,52 @@
"""
CRUD operations for Item model.
"""
from typing import List, Optional
from sqlalchemy.orm import Session
from app.models.item import Item
from app.schemas.item import ItemCreate, ItemUpdate
from app.services.crud.base import CRUDBase
class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]):
"""CRUD operations for Item model."""
def get_by_title(self, db: Session, *, title: str) -> Optional[Item]:
"""
Get an item by title.
Args:
db: Database session
title: Item title
Returns:
Optional item
"""
return db.query(Item).filter(Item.title == title).first()
def get_multi_by_active(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[Item]:
"""
Get multiple active items.
Args:
db: Database session
skip: Number of items to skip
limit: Maximum number of items to return
Returns:
List of active items
"""
return (
db.query(Item)
.filter(Item.is_active == True) # noqa: E712
.offset(skip)
.limit(limit)
.all()
)
item = CRUDItem(Item)

27
main.py Normal file
View File

@ -0,0 +1,27 @@
"""
REST API Service using FastAPI and SQLite
"""
import uvicorn
from fastapi import FastAPI
from app.api.routes import api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
description="REST API Service using FastAPI and SQLite",
version="0.1.0",
openapi_url=f"{settings.API_V1_STR}/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
app.include_router(api_router, prefix=settings.API_V1_STR)
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 SQLite.
This is a generic SQLite database configuration for Alembic.
For more information on Alembic, see:
http://alembic.zzzcomputing.com/en/latest/

80
migrations/env.py Normal file
View File

@ -0,0 +1,80 @@
"""
Alembic environment configuration.
"""
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# 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.db.base import Base # noqa
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,39 @@
"""Create items table
Revision ID: 20231230_000000
Revises:
Create Date: 2023-12-30 00:00:00
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '20231230_000000'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('item',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=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_item_id'), 'item', ['id'], unique=False)
op.create_index(op.f('ix_item_title'), 'item', ['title'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_item_title'), table_name='item')
op.drop_index(op.f('ix_item_id'), table_name='item')
op.drop_table('item')
# ### end Alembic commands ###

12
requirements.txt Normal file
View File

@ -0,0 +1,12 @@
fastapi>=0.108.0
uvicorn>=0.25.0
sqlalchemy>=2.0.23
alembic>=1.13.0
pydantic>=2.5.2
pydantic-settings>=2.1.0
ruff>=0.1.6
types-requests>=2.31.0.10
typing-extensions>=4.8.0
python-multipart>=0.0.6
pytest>=7.4.3
httpx>=0.25.2