Create FastAPI REST API with SQLite backend

This commit is contained in:
Automated Action 2025-06-03 18:58:32 +00:00
parent 6fca3e6d51
commit 65a415575a
24 changed files with 704 additions and 2 deletions

134
README.md
View File

@ -1,3 +1,133 @@
# FastAPI Application
# Generic REST API with FastAPI and SQLite
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
This is a RESTful API built with FastAPI and SQLite, providing a foundation for building robust web applications with Python.
## Features
- FastAPI framework with automatic API documentation
- SQLAlchemy ORM with SQLite database
- Alembic database migrations
- Repository pattern for database operations
- Pydantic models for data validation
- CORS middleware enabled
- Health check endpoint
- RESTful CRUD operations
## Requirements
- Python 3.8+
## Installation
1. Clone the repository:
```bash
git clone https://github.com/yourusername/genericrestapi.git
cd genericrestapi
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Run database migrations:
```bash
alembic upgrade head
```
## Environment Variables
This application uses the following environment variables:
- None required for basic operation as the app uses SQLite with a fixed path
## Running the Application
Start the development server:
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000.
## API Documentation
Once the application is running, you can access:
- Interactive API documentation: http://localhost:8000/docs
- ReDoc API documentation: http://localhost:8000/redoc
- OpenAPI specification: http://localhost:8000/openapi.json
## API Endpoints
### Health Check
- `GET /health` - Check API health status
### Items API
- `GET /api/v1/items/` - List all items (with pagination)
- `POST /api/v1/items/` - Create a new item
- `GET /api/v1/items/{item_id}` - Get a specific item by ID
- `PUT /api/v1/items/{item_id}` - Update a specific item
- `DELETE /api/v1/items/{item_id}` - Delete a specific item
## Project Structure
```
.
├── alembic.ini # Alembic configuration
├── app/ # Application package
│ ├── api/ # API package
│ │ ├── app.py # FastAPI application instance
│ │ ├── health.py # Health check endpoint
│ │ └── v1/ # API v1 endpoints
│ │ └── routes.py # API route definitions
│ ├── core/ # Core functionality
│ │ ├── config.py # Application configuration
│ │ └── exceptions.py # Custom exception classes
│ └── db/ # Database package
│ ├── models/ # SQLAlchemy models
│ │ └── item.py # Item model definition
│ ├── repositories/ # Repository pattern implementations
│ │ ├── base.py # Base repository class
│ │ └── item.py # Item repository
│ ├── schemas/ # Pydantic schemas
│ │ └── item.py # Item schemas
│ └── session.py # Database session configuration
├── main.py # Application entry point
├── migrations/ # Alembic migrations
│ ├── env.py # Alembic environment
│ ├── README # Migrations README
│ ├── script.py.mako # Migration script template
│ └── versions/ # Migration versions
│ └── 0001_initial_migration.py # Initial migration
└── requirements.txt # Python dependencies
```
## Development
### Running Tests
Tests can be run using pytest:
```bash
pytest
```
### Code Formatting and Linting
This project uses Ruff for linting and code formatting:
```bash
ruff check .
ruff format .
```
## License
[MIT License](LICENSE)

107
alembic.ini Normal file
View File

@ -0,0 +1,107 @@
# 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
# 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.
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# 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

0
app/__init__.py Normal file
View File

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

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

@ -0,0 +1,37 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.utils import get_openapi
from app.api.v1.routes import router as api_router
from app.api.health import router as health_router
app = FastAPI(
title="Generic REST API",
description="A FastAPI REST API with SQLite",
version="0.1.0",
docs_url="/docs",
redoc_url="/redoc",
)
# CORS middleware setup
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(health_router)
app.include_router(api_router, prefix="/api/v1")
# Custom OpenAPI schema endpoint
@app.get("/openapi.json", include_in_schema=False)
async def get_open_api_endpoint():
return get_openapi(
title=app.title,
version=app.version,
description=app.description,
routes=app.routes,
)

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

@ -0,0 +1,9 @@
from fastapi import APIRouter, status
router = APIRouter(tags=["health"])
@router.get("/health", status_code=status.HTTP_200_OK)
def health_check():
"""Health check endpoint to verify the API is running."""
return {"status": "healthy"}

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

91
app/api/v1/routes.py Normal file
View File

@ -0,0 +1,91 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from app.db.repositories import item_repository
from app.db.schemas.item import Item, ItemCreate, ItemUpdate
from app.db.session import get_db
router = APIRouter(tags=["items"])
@router.get("/items/", response_model=List[Item])
def read_items(
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=100),
db: Session = Depends(get_db),
):
"""
Retrieve items with pagination support.
"""
items = item_repository.get_multi(db=db, skip=skip, limit=limit)
return items
@router.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
def create_item(
item_in: ItemCreate,
db: Session = Depends(get_db),
):
"""
Create a new item.
"""
item = item_repository.create(db=db, obj_in=item_in)
return item
@router.get("/items/{item_id}", response_model=Item)
def read_item(
item_id: int,
db: Session = Depends(get_db),
):
"""
Get item by ID.
"""
item = item_repository.get(db=db, id=item_id)
if item is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found",
)
return item
@router.put("/items/{item_id}", response_model=Item)
def update_item(
item_id: int,
item_in: ItemUpdate,
db: Session = Depends(get_db),
):
"""
Update an item.
"""
item = item_repository.get(db=db, id=item_id)
if item is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found",
)
item = item_repository.update(db=db, db_obj=item, obj_in=item_in)
return item
@router.delete(
"/items/{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 = item_repository.get(db=db, id=item_id)
if item is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found",
)
item_repository.remove(db=db, id=item_id)
return None

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

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

@ -0,0 +1,24 @@
from pathlib import Path
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
"""Application settings."""
# API settings
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Generic REST API"
# Database settings
DB_DIR: Path = Path("/app/storage/db")
class Config:
case_sensitive = True
env_file = ".env"
settings = Settings()
# Ensure DB directory exists
settings.DB_DIR.mkdir(parents=True, exist_ok=True)

36
app/core/exceptions.py Normal file
View File

@ -0,0 +1,36 @@
from fastapi import HTTPException, status
class NotFoundError(HTTPException):
"""Exception raised when a resource is not found."""
def __init__(self, detail: str = "Resource not found"):
super().__init__(status_code=status.HTTP_404_NOT_FOUND, detail=detail)
class BadRequestError(HTTPException):
"""Exception raised for bad requests."""
def __init__(self, detail: str = "Bad request"):
super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)
class UnauthorizedError(HTTPException):
"""Exception raised for unauthorized access attempts."""
def __init__(self, detail: str = "Not authorized"):
super().__init__(status_code=status.HTTP_401_UNAUTHORIZED, detail=detail)
class ForbiddenError(HTTPException):
"""Exception raised for forbidden access attempts."""
def __init__(self, detail: str = "Forbidden"):
super().__init__(status_code=status.HTTP_403_FORBIDDEN, detail=detail)
class ConflictError(HTTPException):
"""Exception raised for resource conflicts."""
def __init__(self, detail: str = "Resource conflict"):
super().__init__(status_code=status.HTTP_409_CONFLICT, detail=detail)

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

View File

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

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

@ -0,0 +1,17 @@
from sqlalchemy import Column, Integer, String, Text, DateTime, func
from app.db.session import Base
class Item(Base):
"""Database model for items."""
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(100), nullable=False, index=True)
description = Column(Text, nullable=True)
created_at = Column(DateTime, default=func.now(), nullable=False)
updated_at = Column(
DateTime, default=func.now(), onupdate=func.now(), nullable=False
)

View File

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

43
app/db/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 data."""
name: str = Field(..., min_length=1, max_length=100, description="The item name")
description: Optional[str] = Field(None, description="The item description")
class ItemCreate(ItemBase):
"""Schema for creating a new item."""
pass
class ItemUpdate(BaseModel):
"""Schema for updating an existing item."""
name: Optional[str] = Field(
None, min_length=1, max_length=100, description="The item name"
)
description: Optional[str] = Field(None, description="The item description")
class ItemInDB(ItemBase):
"""Schema for item as stored in the database."""
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class Item(ItemInDB):
"""Schema for item returned to clients."""
pass

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

@ -0,0 +1,28 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
# Ensure the database directory exists
DB_DIR = settings.DB_DIR
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()
def get_db():
"""Dependency for getting database session."""
db = SessionLocal()
try:
yield db
finally:
db.close()

4
main.py Normal file
View File

@ -0,0 +1,4 @@
import uvicorn
if __name__ == "__main__":
uvicorn.run("app.api.app:app", host="0.0.0.0", port=8000, reload=True)

3
migrations/README Normal file
View File

@ -0,0 +1,3 @@
Generic single-database configuration with Alembic.
This configuration for Alembic is used to manage database migrations for the FastAPI REST API project.

82
migrations/env.py Normal file
View File

@ -0,0 +1,82 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from app.db.session import Base
from app.db.models import Item # noqa
# 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
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,
)
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, # Enable batch mode 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,38 @@
"""Initial migration
Revision ID: 0001
Revises:
Create Date: 2023-08-01 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "0001"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# Create items table
op.create_table(
"items",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.String(length=100), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
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)
def downgrade() -> None:
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")

View File

@ -0,0 +1 @@
# This file ensures the versions directory is a proper Python package.

22
requirements.txt Normal file
View File

@ -0,0 +1,22 @@
# FastAPI and server dependencies
fastapi>=0.100.0
uvicorn>=0.22.0
python-multipart>=0.0.6
email-validator>=2.0.0
# SQLAlchemy ORM
sqlalchemy>=2.0.0
# Alembic for database migrations
alembic>=1.11.0
# Pydantic for data validation
pydantic>=2.0.0
pydantic-settings>=2.0.0
# Dev tools
ruff>=0.0.270
pytest>=7.3.1
# Typing extensions
typing-extensions>=4.6.0