Create FastAPI REST API with SQLite

- Set up project structure and dependencies
- Create database models with SQLAlchemy
- Implement API endpoints for CRUD operations
- Set up Alembic for database migrations
- Add health check endpoint
- Configure Ruff for linting
- Update documentation in README
This commit is contained in:
Automated Action 2025-05-29 10:18:27 +00:00
parent c12e283074
commit 93c528a258
25 changed files with 654 additions and 2 deletions

101
README.md
View File

@ -1,3 +1,100 @@
# FastAPI Application
# QuickRestAPI
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A simple REST API built with FastAPI and SQLite.
## Features
- FastAPI framework for high performance
- SQLite database with SQLAlchemy ORM
- Alembic database migrations
- Pydantic for data validation
- RESTful CRUD operations on items
- Health check endpoint
- OpenAPI documentation
## Project Structure
```
/
├── app/
│ ├── api/
│ │ └── v1/
│ │ ├── endpoints/
│ │ │ └── items.py
│ │ └── api.py
│ ├── core/
│ │ └── config.py
│ ├── db/
│ │ ├── base.py
│ │ ├── base_class.py
│ │ └── session.py
│ ├── models/
│ │ └── item.py
│ ├── schemas/
│ │ └── item.py
│ └── storage/
│ └── db/
├── migrations/
│ └── versions/
│ └── initial_migration.py
├── alembic.ini
├── main.py
└── requirements.txt
```
## Installation
1. Clone the repository
2. Install dependencies:
```bash
pip install -r requirements.txt
```
## Running the Application
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000
## API Documentation
Once the application is running, you can access:
- Swagger UI documentation: http://localhost:8000/docs
- ReDoc documentation: http://localhost:8000/redoc
- OpenAPI JSON: http://localhost:8000/openapi.json
## API Endpoints
| Method | URL | Description |
|--------|---------------------|---------------------------|
| GET | /health | Health check |
| 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 |
## Database Migrations
Initialize the database:
```bash
alembic upgrade head
```
## Development
Create a new migration after modifying models:
```bash
alembic revision --autogenerate -m "Description of changes"
```
Apply migrations:
```bash
alembic upgrade head
```

106
alembic.ini Normal file
View File

@ -0,0 +1,106 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(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 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: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

1
app/__init__.py Normal file
View File

@ -0,0 +1 @@
# This is intentionally left empty to make app a proper Python package

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

@ -0,0 +1 @@
# This is intentionally left empty to make app/api a proper Python package

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

@ -0,0 +1 @@
# This is intentionally left empty to make app/api/v1 a proper Python package

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

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

View File

@ -0,0 +1 @@
# This is intentionally left empty to make app/api/v1/endpoints a proper Python package

View File

@ -0,0 +1,74 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import models, schemas
from app.db.session import get_db
router = APIRouter()
@router.get("/", response_model=List[schemas.Item])
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
"""
Retrieve items with pagination.
"""
items = db.query(models.Item).offset(skip).limit(limit).all()
return items
@router.post("/", response_model=schemas.Item, status_code=status.HTTP_201_CREATED)
def create_item(item_in: schemas.ItemCreate, db: Session = Depends(get_db)):
"""
Create new item.
"""
item = models.Item(**item_in.model_dump())
db.add(item)
db.commit()
db.refresh(item)
return item
@router.get("/{item_id}", response_model=schemas.Item)
def read_item(item_id: int, db: Session = Depends(get_db)):
"""
Get item by ID.
"""
item = db.query(models.Item).filter(models.Item.id == item_id).first()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return item
@router.put("/{item_id}", response_model=schemas.Item)
def update_item(item_id: int, item_in: schemas.ItemUpdate, db: Session = Depends(get_db)):
"""
Update an item.
"""
item = db.query(models.Item).filter(models.Item.id == item_id).first()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
update_data = item_in.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(item, field, value)
db.add(item)
db.commit()
db.refresh(item)
return item
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_item(item_id: int, db: Session = Depends(get_db)):
"""
Delete an item.
"""
item = db.query(models.Item).filter(models.Item.id == item_id).first()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
db.delete(item)
db.commit()
return None

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

@ -0,0 +1 @@
# This is intentionally left empty to make app/core a proper Python package

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

@ -0,0 +1,38 @@
from pathlib import Path
from typing import Optional
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
# Base settings
PROJECT_NAME: str = "QuickRestAPI"
PROJECT_DESCRIPTION: str = "A simple REST API built with FastAPI and SQLite"
PROJECT_VERSION: str = "0.1.0"
# Server settings
HOST: str = "0.0.0.0"
PORT: int = 8000
DEBUG: bool = True
# Database settings
DB_DIR: Path = Path("/app") / "storage" / "db"
SQLALCHEMY_DATABASE_URL: Optional[str] = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Ensure DB directory exists
self.DB_DIR.mkdir(parents=True, exist_ok=True)
# Set database URL if not provided
if self.SQLALCHEMY_DATABASE_URL is None:
self.SQLALCHEMY_DATABASE_URL = f"sqlite:///{self.DB_DIR}/db.sqlite"
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
case_sensitive = True
settings = Settings()

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

@ -0,0 +1 @@
# This is intentionally left empty to make app/db a proper Python package

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

@ -0,0 +1,3 @@
# Import all the models here for Alembic to discover
from app.db.base_class import Base # noqa
from app.models.item import Item # noqa

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

@ -0,0 +1,14 @@
from typing import Any
from sqlalchemy.ext.declarative import as_declarative, declared_attr
@as_declarative()
class Base:
id: Any
__name__: str
# Generate tablename automatically
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()

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

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

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

@ -0,0 +1 @@
# This is intentionally left empty to make app/models a proper Python package

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

@ -0,0 +1,14 @@
from sqlalchemy import Boolean, Column, Integer, String, Text
from sqlalchemy.sql import func
from sqlalchemy.sql.sqltypes import DateTime
from app.db.base_class import Base
class Item(Base):
id = Column(Integer, primary_key=True, index=True)
title = Column(String(100), index=True)
description = Column(Text, nullable=True)
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())

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

@ -0,0 +1 @@
# This is intentionally left empty to make app/schemas a proper Python package

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

@ -0,0 +1,43 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class ItemBase(BaseModel):
"""Base schema for Item with common attributes."""
title: str = Field(..., min_length=1, max_length=100, description="Item title")
description: Optional[str] = Field(None, description="Optional item description")
is_active: bool = Field(True, description="Item status")
class ItemCreate(ItemBase):
"""Schema for creating a new Item."""
pass
class ItemUpdate(BaseModel):
"""Schema for updating an existing Item."""
title: Optional[str] = Field(None, min_length=1, max_length=100, description="Item title")
description: Optional[str] = Field(None, description="Optional item description")
is_active: Optional[bool] = Field(None, description="Item status")
class ItemInDBBase(ItemBase):
"""Base schema for Item as stored in DB with ID and timestamps."""
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True
class Item(ItemInDBBase):
"""Schema for returning an Item."""
pass

54
main.py Normal file
View File

@ -0,0 +1,54 @@
import uvicorn
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from app.api.v1.api import api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
description=settings.PROJECT_DESCRIPTION,
version=settings.PROJECT_VERSION,
docs_url="/docs",
redoc_url="/redoc",
)
app.include_router(api_router, prefix="/api/v1")
@app.get("/health", status_code=200)
async def health_check():
"""Health check endpoint."""
return {"status": "ok"}
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title=app.title,
version=app.version,
description=app.description,
routes=app.routes,
)
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
@app.get("/openapi.json", include_in_schema=False)
async def get_openapi_schema():
return app.openapi_schema
if __name__ == "__main__":
uvicorn.run(
"main:app",
host=settings.HOST,
port=settings.PORT,
reload=settings.DEBUG,
)

1
migrations/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration with SQLite.

83
migrations/env.py Normal file
View File

@ -0,0 +1,83 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# Import Base for metadata
from app.db.base 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, # Important 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, # Important 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,34 @@
"""initial migration
Revision ID: 001
Revises:
Create Date: 2023-09-26
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.sql import func
# revision identifiers, used by Alembic.
revision = "001"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# Create items table
op.create_table(
"item",
sa.Column("id", sa.Integer(), primary_key=True, index=True),
sa.Column("title", sa.String(100), index=True),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("is_active", sa.Boolean(), default=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=func.now()),
sa.Column("updated_at", sa.DateTime(timezone=True), onupdate=func.now()),
)
def downgrade() -> None:
op.drop_table("item")

21
pyproject.toml Normal file
View File

@ -0,0 +1,21 @@
[tool.ruff]
line-length = 100
target-version = "py310"
[tool.ruff.lint]
select = ["E", "F", "I", "B", "W", "C"]
ignore = ["B008"] # Ignore the warning about function calls in argument defaults
[tool.ruff.lint.isort]
known-first-party = ["app"]
combine-as-imports = true
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
inline-quotes = "double"
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false
line-ending = "auto"

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
python-dotenv>=1.0.0
ruff>=0.0.290