Create comprehensive FastAPI REST API service

- Set up FastAPI application with CORS support
- Implement SQLAlchemy models and database session management
- Create CRUD API endpoints for items management
- Configure Alembic for database migrations
- Add health check and service info endpoints
- Include comprehensive documentation and project structure
- Integrate Ruff for code quality and formatting
This commit is contained in:
Automated Action 2025-06-19 04:39:38 +00:00
parent 6bc58d7461
commit 55fa6c2bbd
18 changed files with 429 additions and 2 deletions

110
README.md
View File

@ -1,3 +1,109 @@
# FastAPI Application
# REST API Service
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A comprehensive REST API built with FastAPI, SQLAlchemy, and SQLite.
## Features
- **FastAPI**: Modern, fast web framework for building APIs
- **SQLAlchemy**: SQL toolkit and Object-Relational Mapping (ORM) library
- **SQLite**: Lightweight database for data persistence
- **Alembic**: Database migration tool
- **CORS**: Cross-Origin Resource Sharing enabled for all origins
- **Health Check**: Built-in health monitoring endpoint
- **API Documentation**: Automatic interactive API docs via OpenAPI/Swagger
## Project Structure
```
.
├── main.py # Application entry point
├── requirements.txt # Python dependencies
├── alembic.ini # Alembic configuration
├── alembic/ # Database migrations
│ ├── env.py
│ ├── script.py.mako
│ └── versions/
└── app/
├── api/ # API routes
│ ├── items.py # Items CRUD endpoints
│ └── routes.py # Main router
├── db/ # Database configuration
│ ├── base.py # SQLAlchemy Base
│ └── session.py # Database session
├── models/ # SQLAlchemy models
│ └── item.py # Item model
└── schemas/ # Pydantic schemas
└── item.py # Item schemas
```
## Installation
1. Install dependencies:
```bash
pip install -r requirements.txt
```
2. Run database migrations:
```bash
alembic upgrade head
```
## Running the Application
Start the server with uvicorn:
```bash
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
```
The API will be available at:
- **API Base**: http://localhost:8000
- **Interactive Docs**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc
- **OpenAPI Schema**: http://localhost:8000/openapi.json
## API Endpoints
### Core Endpoints
- `GET /` - Service information
- `GET /health` - Health check
### Items API (`/api/v1/items`)
- `POST /` - Create a new item
- `GET /` - List all items (with pagination)
- `GET /{item_id}` - Get item by ID
- `PUT /{item_id}` - Update item by ID
- `DELETE /{item_id}` - Delete item by ID
## Database
The application uses SQLite with the database file stored at `/app/storage/db/db.sqlite`.
### Running Migrations
Create a new migration:
```bash
alembic revision --autogenerate -m "Description of changes"
```
Apply migrations:
```bash
alembic upgrade head
```
## Development
### Code Quality
The project uses Ruff for code formatting and linting:
```bash
ruff check .
ruff format .
```
### Environment Variables
No environment variables are required for basic operation. The application uses SQLite with a default file path.
## License
This project is open source and available under the MIT License.

41
alembic.ini Normal file
View File

@ -0,0 +1,41 @@
[alembic]
script_location = alembic
file_template = %%(year)d%%(month).2d%%(day).2d_%%(hour).2d%%(minute).2d%%(second).2d_%%(slug)s
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
[post_write_hooks]
[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

52
alembic/env.py Normal file
View File

@ -0,0 +1,52 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
import sys
from pathlib import Path
# Add the project root to sys.path
sys.path.insert(0, str(Path(__file__).parent.parent))
from app.db.base import Base
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
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() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

24
alembic/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,35 @@
"""Initial migration
Revision ID: 001
Revises:
Create Date: 2024-12-19 12:00:00.000000
"""
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:
op.create_table('items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('description', sa.String(), 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)
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')

0
app/__init__.py Normal file
View File

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

53
app/api/items.py Normal file
View File

@ -0,0 +1,53 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.db.session import get_db
from app.models.item import Item
from app.schemas.item import Item as ItemSchema, ItemCreate, ItemUpdate
router = APIRouter()
@router.post("/", response_model=ItemSchema)
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
db_item = Item(**item.dict())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@router.get("/", response_model=List[ItemSchema])
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
items = db.query(Item).offset(skip).limit(limit).all()
return items
@router.get("/{item_id}", response_model=ItemSchema)
def read_item(item_id: int, db: Session = Depends(get_db)):
item = db.query(Item).filter(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=ItemSchema)
def update_item(item_id: int, item_update: ItemUpdate, db: Session = Depends(get_db)):
db_item = db.query(Item).filter(Item.id == item_id).first()
if db_item is None:
raise HTTPException(status_code=404, detail="Item not found")
update_data = item_update.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(db_item, field, value)
db.commit()
db.refresh(db_item)
return db_item
@router.delete("/{item_id}")
def delete_item(item_id: int, db: Session = Depends(get_db)):
db_item = db.query(Item).filter(Item.id == item_id).first()
if db_item is None:
raise HTTPException(status_code=404, detail="Item not found")
db.delete(db_item)
db.commit()
return {"message": "Item deleted successfully"}

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

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

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()

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

@ -0,0 +1,22 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from pathlib import Path
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)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

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

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

@ -0,0 +1,13 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.sql import func
from app.db.base import Base
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True, nullable=False)
description = Column(String, 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())

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

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

@ -0,0 +1,24 @@
from pydantic import BaseModel
from datetime import datetime
from typing import Optional
class ItemBase(BaseModel):
name: str
description: Optional[str] = None
is_active: bool = True
class ItemCreate(ItemBase):
pass
class ItemUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
is_active: Optional[bool] = None
class Item(ItemBase):
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True

41
main.py Normal file
View File

@ -0,0 +1,41 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.routes import api_router
from app.db.session import engine
from app.db.base import Base
app = FastAPI(
title="REST API Service",
description="A comprehensive REST API built with FastAPI",
version="1.0.0",
openapi_url="/openapi.json"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Base.metadata.create_all(bind=engine)
app.include_router(api_router, prefix="/api/v1")
@app.get("/")
async def root():
return {
"title": "REST API Service",
"documentation": "/docs",
"health": "/health"
}
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "REST API Service"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)

7
requirements.txt Normal file
View File

@ -0,0 +1,7 @@
fastapi==0.104.1
uvicorn[standard]==0.24.0
sqlalchemy==2.0.23
alembic==1.12.1
python-multipart==0.0.6
pydantic==2.5.0
ruff==0.1.6