Implement QuickSimpleAPI with FastAPI and SQLite

This commit is contained in:
Automated Action 2025-06-05 22:08:51 +00:00
parent 5d55003cf7
commit f5a9c38b60
25 changed files with 597 additions and 2 deletions

View File

@ -1,3 +1,96 @@
# FastAPI Application # QuickSimpleAPI
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A simple FastAPI application with SQLite database integration for basic CRUD operations.
## Features
- FastAPI with SQLite backend
- CRUD operations for items
- Alembic for database migrations
- Health check endpoint
- OpenAPI documentation
## Project Structure
```
/
├── app/
│ ├── api/
│ │ ├── deps.py
│ │ ├── health.py
│ │ └── v1/
│ │ ├── api.py
│ │ └── endpoints/
│ │ └── items.py
│ ├── core/
│ │ └── config.py
│ ├── db/
│ │ ├── base.py
│ │ └── session.py
│ ├── models/
│ │ └── item.py
│ └── schemas/
│ └── item.py
├── migrations/
│ ├── versions/
│ │ └── 001_initial_migration.py
│ ├── env.py
│ ├── README
│ └── script.py.mako
├── alembic.ini
├── main.py
└── requirements.txt
```
## Installation
1. Clone the repository
2. Install the dependencies:
```bash
pip install -r requirements.txt
```
## Running the Application
To run 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 the API documentation at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
- `GET /`: Root endpoint with API information
- `GET /health`: Health check endpoint
- `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 a specific item
- `DELETE /api/v1/items/{item_id}`: Delete a specific item
## Database Migrations
This project uses Alembic for database migrations. To run the migrations:
```bash
alembic upgrade head
```
To create a new migration:
```bash
alembic revision --autogenerate -m "Description of changes"
```
## Environment Variables
No environment variables are required for basic operation.

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 = %%(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 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 using absolute path
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

0
app/__init__.py Normal file
View File

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

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

@ -0,0 +1,11 @@
from typing import Generator
from app.db.session import SessionLocal
def get_db() -> Generator:
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1,21 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.api import deps
router = APIRouter()
@router.get("/health")
def health_check(db: Session = Depends(deps.get_db)):
"""
Check the health of the application.
"""
try:
# Try to execute a simple query to check database connection
db.execute("SELECT 1")
db_status = "healthy"
except Exception:
db_status = "unhealthy"
return {"status": "healthy", "database": db_status}

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

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

View File

@ -0,0 +1,99 @@
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api import deps
from app.models.item import Item
from app.schemas.item import Item as ItemSchema
from app.schemas.item import ItemCreate, ItemUpdate
router = APIRouter()
@router.get("/", response_model=List[ItemSchema])
def read_items(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve items.
"""
items = db.query(Item).offset(skip).limit(limit).all()
return items
@router.post("/", response_model=ItemSchema)
def create_item(
*,
db: Session = Depends(deps.get_db),
item_in: ItemCreate,
) -> Any:
"""
Create new item.
"""
item = Item(title=item_in.title, description=item_in.description)
db.add(item)
db.commit()
db.refresh(item)
return item
@router.get("/{item_id}", response_model=ItemSchema)
def read_item(
*,
db: Session = Depends(deps.get_db),
item_id: int,
) -> Any:
"""
Get item by ID.
"""
item = db.query(Item).filter(Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
@router.put("/{item_id}", response_model=ItemSchema)
def update_item(
*,
db: Session = Depends(deps.get_db),
item_id: int,
item_in: ItemUpdate,
) -> Any:
"""
Update an item.
"""
item = db.query(Item).filter(Item.id == item_id).first()
if not item:
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(
*,
db: Session = Depends(deps.get_db),
item_id: int,
) -> Any:
"""
Delete an item.
"""
item = db.query(Item).filter(Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
db.delete(item)
db.commit()
return None

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

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

@ -0,0 +1,12 @@
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "QuickSimpleAPI"
class Config:
env_file = ".env"
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()

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

@ -0,0 +1,14 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
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)

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

@ -0,0 +1,3 @@
from app.models.item import Item # noqa
# Import all models here for Alembic to detect

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

@ -0,0 +1,11 @@
from sqlalchemy import Column, Integer, String, Text
from app.db.base import Base
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(100), index=True)
description = Column(Text, nullable=True)

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

@ -0,0 +1 @@
from app.schemas.item import Item, ItemCreate, ItemUpdate # noqa

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

@ -0,0 +1,27 @@
from typing import Optional
from pydantic import BaseModel
class ItemBase(BaseModel):
title: str
description: Optional[str] = None
class ItemCreate(ItemBase):
pass
class ItemUpdate(ItemBase):
title: Optional[str] = None
class ItemInDBBase(ItemBase):
id: int
class Config:
from_attributes = True
class Item(ItemInDBBase):
pass

52
main.py Normal file
View File

@ -0,0 +1,52 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import RedirectResponse
from app.api import health
from app.api.v1.api import api_router
from app.core.config import settings
from app.db.base import Base
from app.db.session import engine
# Create database tables
Base.metadata.create_all(bind=engine)
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url="/openapi.json",
)
# Set up CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(api_router, prefix=settings.API_V1_STR)
app.include_router(health.router)
@app.get("/", tags=["root"])
async def root():
"""
Root endpoint that provides basic API information.
"""
return {"name": settings.PROJECT_NAME, "docs": "/docs", "health": "/health"}
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_redirect():
"""
Redirect to docs
"""
return RedirectResponse(url="/docs")
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

1
migrations/README Normal file
View File

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

87
migrations/env.py Normal file
View File

@ -0,0 +1,87 @@
import os
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# Add the parent directory to sys.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
# Import the SQLAlchemy Base and all models
from app.db.base import Base
import app.models # 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.
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():
"""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,37 @@
"""Initial migration - Create items table
Revision ID: 001
Revises:
Create Date: 2023-09-14
"""
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():
# Create items table
op.create_table(
"items",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("title", sa.String(length=100), nullable=False),
sa.Column("description", sa.Text(), 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)
def downgrade():
# Drop items table
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")

8
requirements.txt Normal file
View File

@ -0,0 +1,8 @@
fastapi==0.103.1
uvicorn==0.23.2
sqlalchemy==2.0.20
alembic==1.12.0
pydantic==2.3.0
pydantic-settings==2.0.3
python-dotenv==1.0.0
ruff==0.0.290