Create FastAPI REST API with SQLite database

- Set up project structure with FastAPI and SQLAlchemy
- Configure SQLite database with async support
- Implement CRUD endpoints for items resource
- Add health endpoint for monitoring
- Set up Alembic migrations
- Create comprehensive documentation

generated with BackendIM... (backend.im)
This commit is contained in:
Automated Action 2025-05-14 01:20:38 +00:00
parent c186e177dc
commit f047098f40
18 changed files with 558 additions and 2 deletions

View File

@ -1,3 +1,73 @@
# FastAPI Application
# Quick REST API Service
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A fast, lightweight REST API service built with FastAPI and SQLite.
## Features
- **FastAPI Framework**: High-performance async API framework
- **SQLite Database**: Simple, file-based database with SQLAlchemy ORM
- **Async Support**: Full async/await pattern for high concurrency
- **Migrations**: Database versioning with Alembic
- **API Documentation**: Auto-generated OpenAPI docs
- **Health Endpoint**: Monitoring endpoint at `/api/v1/health`
- **CRUD Operations**: Complete REST API for item resources
## Project Structure
```
.
├── app
│ ├── api
│ │ └── v1
│ │ ├── __init__.py
│ │ ├── health.py
│ │ └── items.py
│ ├── core
│ │ └── config.py
│ ├── db
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── session.py
│ │ └── migrations/
│ ├── models
│ │ ├── __init__.py
│ │ └── item.py
│ └── schemas
│ ├── __init__.py
│ └── item.py
├── alembic.ini
├── main.py
├── requirements.txt
└── README.md
```
## Installation
1. Clone the repository
2. Install dependencies:
```bash
pip install -r requirements.txt
```
## Running the Application
Start the server with:
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000.
API documentation is available at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
- `GET /api/v1/health` - Check API health
- `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 an item
- `DELETE /api/v1/items/{item_id}` - Delete an item

103
alembic.ini Normal file
View File

@ -0,0 +1,103 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = app/db/migrations
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# 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 app/db/migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:app/db/migrations/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# 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 REVISION_SCRIPT_FILENAME
# 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

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

@ -0,0 +1,6 @@
from fastapi import APIRouter
from app.api.v1 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"])

17
app/api/v1/health.py Normal file
View File

@ -0,0 +1,17 @@
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import get_db
router = APIRouter()
@router.get("")
async def health_check(db: AsyncSession = Depends(get_db)):
"""
Health check endpoint to verify API and database connectivity.
"""
return {
"status": "healthy",
"database": "connected",
"message": "API is running correctly"
}

63
app/api/v1/items.py Normal file
View File

@ -0,0 +1,63 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from app.db.session import get_db
from app.models.item import Item
from app.schemas.item import ItemCreate, ItemResponse, ItemUpdate
router = APIRouter()
@router.post("", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
async def create_item(item_in: ItemCreate, db: AsyncSession = Depends(get_db)):
"""Create a new item."""
db_item = Item(**item_in.model_dump())
db.add(db_item)
await db.commit()
await db.refresh(db_item)
return db_item
@router.get("", response_model=List[ItemResponse])
async def read_items(skip: int = 0, limit: int = 100, db: AsyncSession = Depends(get_db)):
"""Get all items."""
result = await db.execute(select(Item).offset(skip).limit(limit))
items = result.scalars().all()
return items
@router.get("/{item_id}", response_model=ItemResponse)
async def read_item(item_id: int, db: AsyncSession = Depends(get_db)):
"""Get item by ID."""
result = await db.execute(select(Item).filter(Item.id == item_id))
item = result.scalars().first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
@router.put("/{item_id}", response_model=ItemResponse)
async def update_item(item_id: int, item_in: ItemUpdate, db: AsyncSession = Depends(get_db)):
"""Update an item."""
result = await db.execute(select(Item).filter(Item.id == item_id))
item = result.scalars().first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
update_data = item_in.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(item, key, value)
await db.commit()
await db.refresh(item)
return item
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: int, db: AsyncSession = Depends(get_db)):
"""Delete an item."""
result = await db.execute(select(Item).filter(Item.id == item_id))
item = result.scalars().first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
await db.delete(item)
await db.commit()
return None

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

@ -0,0 +1,29 @@
from typing import List, Optional, Union
from pathlib import Path
from pydantic import AnyHttpUrl, validator
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Quick REST API Service"
# CORS settings
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
@validator("BACKEND_CORS_ORIGINS", pre=True)
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
if isinstance(v, str) and not v.startswith("["):
return [i.strip() for i in v.split(",")]
elif isinstance(v, (list, str)):
return v
raise ValueError(v)
# Database settings
DB_DIR = Path("/app/storage/db")
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
class Config:
case_sensitive = True
settings = Settings()

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

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

@ -0,0 +1,3 @@
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

92
app/db/migrations/env.py Normal file
View File

@ -0,0 +1,92 @@
import asyncio
from logging.config import fileConfig
from pathlib import Path
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import AsyncEngine
from alembic import context
# 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
from app.db.base import Base
from app.models import Item # Import all your models here
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.
DB_DIR = Path("/app/storage/db")
DB_DIR.mkdir(parents=True, exist_ok=True)
config.set_main_option('sqlalchemy.url', f"sqlite+aiosqlite:///{DB_DIR}/db.sqlite")
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 do_run_migrations(connection):
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async 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 = AsyncEngine(
engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
future=True,
)
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())

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,40 @@
"""Initial migration
Revision ID: 8675309dee
Revises:
Create Date: 2025-05-14
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8675309dee'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('items',
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(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_items_id'), 'items', ['id'], unique=False)
op.create_index(op.f('ix_items_title'), 'items', ['title'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_items_title'), table_name='items')
op.drop_index(op.f('ix_items_id'), table_name='items')
op.drop_table('items')
# ### end Alembic commands ###

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

@ -0,0 +1,32 @@
from pathlib import Path
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from typing import Generator
DB_DIR = Path("/app/storage/db")
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite+aiosqlite:///{DB_DIR}/db.sqlite"
engine = create_async_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False},
echo=True
)
SessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=engine,
class_=AsyncSession
)
async def get_db() -> Generator[AsyncSession, None, None]:
"""
Dependency for getting async db session.
"""
async with SessionLocal() as session:
try:
yield session
finally:
await session.close()

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

@ -0,0 +1 @@
from app.models.item import Item

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

@ -0,0 +1,12 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime, func
from app.db.base import Base
class Item(Base):
__tablename__ = "items"
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, server_default=func.now())
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())

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

@ -0,0 +1 @@
from app.schemas.item import ItemBase, ItemCreate, ItemUpdate, ItemResponse

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

@ -0,0 +1,27 @@
from pydantic import BaseModel
from datetime import datetime
from typing import Optional
# Shared properties
class ItemBase(BaseModel):
title: str
description: Optional[str] = None
is_active: Optional[bool] = True
# Properties to receive on item creation
class ItemCreate(ItemBase):
pass
# Properties to receive on item update
class ItemUpdate(ItemBase):
title: Optional[str] = None
is_active: Optional[bool] = None
# Properties to return to client
class ItemResponse(ItemBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True

28
main.py Normal file
View File

@ -0,0 +1,28 @@
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1 import api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
# Set all CORS enabled origins
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=["*"],
)
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)

8
requirements.txt Normal file
View File

@ -0,0 +1,8 @@
fastapi>=0.103.1
uvicorn>=0.23.2
sqlalchemy>=2.0.21
alembic>=1.12.0
pydantic>=2.4.2
pydantic-settings>=2.0.3
aiosqlite>=0.19.0
ruff>=0.0.290