diff --git a/README.md b/README.md index e8acfba..0740482 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,59 @@ -# FastAPI Application +# REST API Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A REST API service built with FastAPI and SQLite. + +## Features + +- FastAPI web framework +- SQLite database with SQLAlchemy ORM +- Database migrations with Alembic +- CRUD operations for Items +- CORS enabled for all origins +- Health check endpoint +- Interactive API documentation + +## Installation + +1. Install dependencies: +```bash +pip install -r requirements.txt +``` + +## Running the Application + +Start the development server: +```bash +uvicorn main:app --reload --host 0.0.0.0 --port 8000 +``` + +The API will be available at: +- Main API: http://localhost:8000 +- Interactive docs: http://localhost:8000/docs +- OpenAPI spec: http://localhost:8000/openapi.json +- Health check: http://localhost:8000/health + +## API Endpoints + +### Items CRUD +- `GET /items/` - List all items +- `POST /items/` - Create a new item +- `GET /items/{item_id}` - Get a specific item +- `PUT /items/{item_id}` - Update a specific item +- `DELETE /items/{item_id}` - Delete a specific item + +### System +- `GET /` - API information +- `GET /health` - Health check + +## Database + +The application uses SQLite database stored at `/app/storage/db/db.sqlite`. + +Database migrations are managed with Alembic. To run migrations: +```bash +alembic upgrade head +``` + +## Environment Variables + +No environment variables are required for basic operation. diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..017f263 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,41 @@ +[alembic] +script_location = alembic +prepend_sys_path = . +version_path_separator = os +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 \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..779b93c --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,49 @@ +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 + +sys.path.append(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() \ No newline at end of file diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..37d0cac --- /dev/null +++ b/alembic/script.py.mako @@ -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"} \ No newline at end of file diff --git a/alembic/versions/001_initial_migration.py b/alembic/versions/001_initial_migration.py new file mode 100644 index 0000000..44ec712 --- /dev/null +++ b/alembic/versions/001_initial_migration.py @@ -0,0 +1,34 @@ +"""Initial migration + +Revision ID: 001 +Revises: +Create Date: 2025-06-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=True), + sa.Column('description', sa.String(), 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') \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/crud.py b/app/crud.py new file mode 100644 index 0000000..1b21454 --- /dev/null +++ b/app/crud.py @@ -0,0 +1,33 @@ +from sqlalchemy.orm import Session +from app.models import Item +from app.schemas import ItemCreate, ItemUpdate + +def get_item(db: Session, item_id: int): + return db.query(Item).filter(Item.id == item_id).first() + +def get_items(db: Session, skip: int = 0, limit: int = 100): + return db.query(Item).offset(skip).limit(limit).all() + +def create_item(db: Session, item: ItemCreate): + db_item = Item(**item.dict()) + db.add(db_item) + db.commit() + db.refresh(db_item) + return db_item + +def update_item(db: Session, item_id: int, item: ItemUpdate): + db_item = db.query(Item).filter(Item.id == item_id).first() + if db_item: + update_data = item.dict(exclude_unset=True) + for key, value in update_data.items(): + setattr(db_item, key, value) + db.commit() + db.refresh(db_item) + return db_item + +def delete_item(db: Session, item_id: int): + db_item = db.query(Item).filter(Item.id == item_id).first() + if db_item: + db.delete(db_item) + db.commit() + return db_item \ No newline at end of file diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..7c2377a --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,3 @@ +from sqlalchemy.ext.declarative import declarative_base + +Base = declarative_base() \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..3864851 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,22 @@ +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) + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..50aafc1 --- /dev/null +++ b/app/models.py @@ -0,0 +1,12 @@ +from sqlalchemy import Column, Integer, String, 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) + description = Column(String) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), onupdate=func.now()) \ No newline at end of file diff --git a/app/schemas.py b/app/schemas.py new file mode 100644 index 0000000..ca40a3e --- /dev/null +++ b/app/schemas.py @@ -0,0 +1,22 @@ +from pydantic import BaseModel +from datetime import datetime +from typing import Optional + +class ItemBase(BaseModel): + name: str + description: Optional[str] = None + +class ItemCreate(ItemBase): + pass + +class ItemUpdate(BaseModel): + name: Optional[str] = None + description: Optional[str] = None + +class Item(ItemBase): + id: int + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..d4c909f --- /dev/null +++ b/main.py @@ -0,0 +1,67 @@ +from fastapi import FastAPI, Depends, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from sqlalchemy.orm import Session +from typing import List + +from app.db.session import get_db, engine +from app.db.base import Base +from app import crud, schemas + +app = FastAPI( + title="REST API Service", + description="A REST API service 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.get("/") +async def root(): + return { + "title": "REST API Service", + "documentation": "/docs", + "health_check": "/health" + } + +@app.get("/health") +async def health_check(): + return {"status": "healthy", "service": "REST API Service"} + +@app.post("/items/", response_model=schemas.Item) +def create_item(item: schemas.ItemCreate, db: Session = Depends(get_db)): + return crud.create_item(db=db, item=item) + +@app.get("/items/", response_model=List[schemas.Item]) +def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): + items = crud.get_items(db, skip=skip, limit=limit) + return items + +@app.get("/items/{item_id}", response_model=schemas.Item) +def read_item(item_id: int, db: Session = Depends(get_db)): + db_item = crud.get_item(db, item_id=item_id) + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + return db_item + +@app.put("/items/{item_id}", response_model=schemas.Item) +def update_item(item_id: int, item: schemas.ItemUpdate, db: Session = Depends(get_db)): + db_item = crud.update_item(db, item_id=item_id, item=item) + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + return db_item + +@app.delete("/items/{item_id}") +def delete_item(item_id: int, db: Session = Depends(get_db)): + db_item = crud.delete_item(db, item_id=item_id) + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + return {"message": "Item deleted successfully"} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..f43f33b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +fastapi==0.104.1 +uvicorn==0.24.0 +sqlalchemy==2.0.23 +alembic==1.12.1 +ruff==0.1.7 \ No newline at end of file