Implement RESTful API using FastAPI and SQLite

- Set up project structure with FastAPI framework
- Implement database models using SQLAlchemy
- Create Alembic migrations for database schema
- Build CRUD endpoints for Items resource
- Add health check endpoint
- Include API documentation with Swagger and ReDoc
- Update README with project documentation
This commit is contained in:
Automated Action 2025-05-18 16:46:51 +00:00
parent 797dacf17e
commit 07301a47e7
23 changed files with 751 additions and 2 deletions

120
README.md
View File

@ -1,3 +1,119 @@
# FastAPI Application
# Generic REST API Service
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A RESTful API built with FastAPI and SQLite.
## Features
- FastAPI framework for high performance
- SQLAlchemy ORM with SQLite database
- Alembic for database migrations
- Pydantic for data validation
- CRUD operations for resources
- API documentation (Swagger UI and ReDoc)
- Health check endpoint
## Project Structure
```
.
├── alembic.ini # Alembic configuration
├── app
│ ├── api # API endpoints
│ │ ├── api.py # Main API router
│ │ ├── endpoints # API endpoint modules
│ │ ├── health.py # Health check endpoint
│ │ └── items.py # Items CRUD endpoints
│ ├── core # Core application components
│ │ └── config.py # Application settings
│ ├── crud # CRUD operations
│ │ └── item.py # Item CRUD
│ ├── db # Database setup
│ │ └── database.py # DB connection, session
│ ├── models # SQLAlchemy models
│ │ └── item.py # Item model
│ ├── schemas # Pydantic schemas
│ │ └── item.py # Item schemas
│ └── storage # Storage for DB and files
│ └── db # Database storage
├── migrations # Alembic migrations
│ ├── env.py # Alembic environment
│ ├── script.py.mako # Migration script template
│ └── versions # Migration versions
│ └── 001_create_items_table.py # First migration
├── main.py # Application entry point
└── requirements.txt # Project dependencies
```
## Installation
### Prerequisites
- Python 3.8+
- pip
### Setup
1. Clone the repository:
```bash
git clone <repository-url>
cd genericrestapiservice-e7xfpj
```
2. Create a virtual environment:
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
3. Install dependencies:
```bash
pip install -r requirements.txt
```
4. Run database migrations:
```bash
alembic upgrade head
```
5. Start the application:
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000.
## API Documentation
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
- Health Check: `GET /api/v1/health`
- List Items: `GET /api/v1/items`
- Create Item: `POST /api/v1/items`
- Get Item: `GET /api/v1/items/{item_id}`
- Update Item: `PUT /api/v1/items/{item_id}`
- Delete Item: `DELETE /api/v1/items/{item_id}`
## Development
### Adding a New Endpoint
1. Create a new module in `app/api/endpoints/`
2. Define your routes using FastAPI's router
3. Add your new router to `app/api/api.py`
### Adding a New Model
1. Define your SQLAlchemy model in `app/models/`
2. Define the Pydantic schemas in `app/schemas/`
3. Create CRUD utilities in `app/crud/`
4. Generate a migration: `alembic revision -m "Add new model"`
5. Edit the migration file in `migrations/versions/`
6. Apply the migration: `alembic upgrade head`

74
alembic.ini Normal file
View 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 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
# SQLite URL example
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/__init__.py Normal file
View File

@ -0,0 +1 @@
# This file is intentionally left empty to make the directory a proper Python package.

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

@ -0,0 +1 @@
# This file is intentionally left empty to make the directory a proper Python package.

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

@ -0,0 +1,9 @@
from fastapi import APIRouter
from app.api.endpoints import items, health
api_router = APIRouter()
# Include all the endpoint routers
api_router.include_router(health.router, prefix="/health", tags=["health"])
api_router.include_router(items.router, prefix="/items", tags=["items"])

View File

@ -0,0 +1 @@
# This file is intentionally left empty to make the directory a proper Python package.

View File

@ -0,0 +1,39 @@
from fastapi import APIRouter, Depends, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.db.database import get_db
router = APIRouter()
class HealthCheck(BaseModel):
status: str
api_version: str
db_status: str
@router.get(
"/",
response_model=HealthCheck,
status_code=status.HTTP_200_OK,
description="Health check for the API"
)
def health_check(db: Session = Depends(get_db)):
"""
Perform a health check for the API
"""
db_status = "healthy"
# Simple DB connection check
try:
# Execute a simple query to check DB connection
db.execute("SELECT 1")
except Exception:
db_status = "unhealthy"
return {
"status": "healthy",
"api_version": "1.0.0",
"db_status": db_status
}

View File

@ -0,0 +1,93 @@
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.crud import get_item, get_items, create_item, update_item, delete_item
from app.db.database import get_db
from app.schemas.item import Item, ItemCreate, ItemUpdate
router = APIRouter()
@router.get("/", response_model=List[Item])
def read_items(
skip: int = 0,
limit: int = 100,
name: Optional[str] = None,
is_active: Optional[bool] = None,
db: Session = Depends(get_db)
):
"""
Retrieve items with optional filtering.
"""
filters = {}
if name is not None:
filters["name"] = name
if is_active is not None:
filters["is_active"] = is_active
return get_items(db, skip=skip, limit=limit, filter_dict=filters)
@router.post("/", response_model=Item, status_code=status.HTTP_201_CREATED)
def create_new_item(
item: ItemCreate,
db: Session = Depends(get_db)
):
"""
Create a new item.
"""
return create_item(db=db, item=item)
@router.get("/{item_id}", response_model=Item)
def read_item(
item_id: int,
db: Session = Depends(get_db)
):
"""
Get a specific item by ID.
"""
db_item = get_item(db=db, item_id=item_id)
if db_item is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found"
)
return db_item
@router.put("/{item_id}", response_model=Item)
def update_existing_item(
item_id: int,
item: ItemUpdate,
db: Session = Depends(get_db)
):
"""
Update an item.
"""
db_item = update_item(db=db, item_id=item_id, item=item)
if db_item is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found"
)
return db_item
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_existing_item(
item_id: int,
db: Session = Depends(get_db)
):
"""
Delete an item.
"""
success = delete_item(db=db, item_id=item_id)
if not success:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found"
)
return None

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

@ -0,0 +1 @@
# This file is intentionally left empty to make the directory a proper Python package.

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

@ -0,0 +1,28 @@
from typing import List
from pydantic import field_validator
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Generic REST API Service"
# CORS configuration
BACKEND_CORS_ORIGINS: List[str] = ["*"]
@field_validator("BACKEND_CORS_ORIGINS")
def validate_cors_origins(cls, v: List[str]) -> List[str]:
"""
Make sure CORS origins are in the correct format
"""
origins = []
for origin in v:
origins.append(origin.strip())
return origins
# Other settings
DEBUG: bool = False
settings = Settings()

15
app/crud/__init__.py Normal file
View File

@ -0,0 +1,15 @@
from app.crud.item import (
get_item,
get_items,
create_item,
update_item,
delete_item
)
__all__ = [
"get_item",
"get_items",
"create_item",
"update_item",
"delete_item"
]

56
app/crud/item.py Normal file
View File

@ -0,0 +1,56 @@
from typing import List, Optional, Dict, Any
from sqlalchemy.orm import Session
from app.models.item import Item
from app.schemas.item import ItemCreate, ItemUpdate
def get_item(db: Session, item_id: int) -> Optional[Item]:
return db.query(Item).filter(Item.id == item_id).first()
def get_items(
db: Session, skip: int = 0, limit: int = 100, filter_dict: Optional[Dict[str, Any]] = None
) -> List[Item]:
query = db.query(Item)
if filter_dict:
for field, value in filter_dict.items():
if hasattr(Item, field):
query = query.filter(getattr(Item, field) == value)
return query.offset(skip).limit(limit).all()
def create_item(db: Session, item: ItemCreate) -> Item:
db_item = Item(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
def update_item(db: Session, item_id: int, item: ItemUpdate) -> Optional[Item]:
db_item = get_item(db, item_id)
if not db_item:
return None
update_data = item.model_dump(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
def delete_item(db: Session, item_id: int) -> bool:
db_item = get_item(db, item_id)
if not db_item:
return False
db.delete(db_item)
db.commit()
return True

27
app/db/database.py Normal file
View File

@ -0,0 +1,27 @@
from pathlib import Path
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
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()
metadata = MetaData()
# Dependency
def get_db() -> Session:
db = SessionLocal()
try:
yield db
finally:
db.close()

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

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

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

@ -0,0 +1,16 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.sql import func
from app.db.database 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())

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

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

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

@ -0,0 +1,40 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field, ConfigDict
class ItemBase(BaseModel):
name: str
description: Optional[str] = None
price: int = Field(description="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 ItemInDBBase(ItemBase):
id: int
created_at: datetime
updated_at: Optional[datetime] = None
model_config = ConfigDict(from_attributes=True)
class Item(ItemInDBBase):
"""Response model for API"""
pass
class ItemInDB(ItemInDBBase):
"""Internal model with potential sensitive data"""
pass

56
main.py Normal file
View File

@ -0,0 +1,56 @@
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
from app.api.api import api_router
from app.core.config import settings
from app.db.database import Base, engine
# Create the database tables if they don't exist
# In production, you'd use Alembic migrations instead
if os.environ.get("ENVIRONMENT") != "production":
Base.metadata.create_all(bind=engine)
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
docs_url=None, # We'll define custom endpoints for docs
redoc_url=None,
)
# Set up CORS middleware
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include our router
app.include_router(api_router, prefix=settings.API_V1_STR)
# Custom documentation endpoints
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
)
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
return get_redoc_html(
openapi_url=app.openapi_url,
title=app.title + " - ReDoc",
)
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 @@
# This file is intentionally left empty to make migrations a proper Python package.

84
migrations/env.py Normal file
View File

@ -0,0 +1,84 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from app.db.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.
if config.config_file_name is not None:
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() -> None:
"""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"},
render_as_batch=True, # For SQLite
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""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, # 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() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,41 @@
"""create items table
Revision ID: 001
Revises:
Create Date: 2023-06-01
"""
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() -> None:
# ### commands auto generated by Alembic - please adjust! ###
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),
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)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
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')
# ### end Alembic commands ###

13
requirements.txt Normal file
View File

@ -0,0 +1,13 @@
fastapi>=0.103.1
uvicorn>=0.23.2
pydantic>=2.4.2
pydantic-settings>=2.0.3
sqlalchemy>=2.0.21
alembic>=1.12.0
python-multipart>=0.0.6
python-jose[cryptography]>=3.3.0
passlib[bcrypt]>=1.7.4
email-validator>=2.0.0
requests>=2.31.0
httpx>=0.25.0
ruff>=0.0.292