diff --git a/README.md b/README.md index e8acfba..c31fcfc 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,55 @@ -# 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, featuring user management endpoints. + +## Features + +- FastAPI framework with automatic API documentation +- SQLite database with SQLAlchemy ORM +- Database migrations with Alembic +- User management CRUD operations +- Health check endpoint +- CORS enabled for all origins + +## API Endpoints + +### Core Endpoints +- `GET /` - Service information +- `GET /health` - Health check +- `GET /docs` - Interactive API documentation +- `GET /redoc` - ReDoc API documentation + +### User Management +- `POST /api/v1/users/` - Create a new user +- `GET /api/v1/users/` - List all users (with pagination) +- `GET /api/v1/users/{user_id}` - Get a specific user +- `PUT /api/v1/users/{user_id}` - Update a user +- `DELETE /api/v1/users/{user_id}` - Delete a user + +## Installation + +1. Install dependencies: +```bash +pip install -r requirements.txt +``` + +2. Run the application: +```bash +python main.py +``` + +The API will be available at `http://localhost:8000` + +## Database + +The application uses SQLite database stored at `/app/storage/db/db.sqlite`. The database schema is managed through Alembic migrations. + +## Environment Variables + +No environment variables are currently required for basic operation. + +## Development + +- API documentation is available at `/docs` (Swagger UI) and `/redoc` (ReDoc) +- The application includes automatic database table creation on startup +- Code formatting and linting is handled by Ruff diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..462797d --- /dev/null +++ b/alembic.ini @@ -0,0 +1,42 @@ +[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..e1ca1aa --- /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 +import os + +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +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_create_users_table.py b/alembic/versions/001_create_users_table.py new file mode 100644 index 0000000..121db4d --- /dev/null +++ b/alembic/versions/001_create_users_table.py @@ -0,0 +1,35 @@ +"""Create users table + +Revision ID: 001 +Revises: +Create Date: 2024-01-01 00: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('users', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('email', sa.String(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + 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_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + + +def downgrade() -> None: + op.drop_index(op.f('ix_users_id'), table_name='users') + op.drop_index(op.f('ix_users_email'), table_name='users') + op.drop_table('users') \ 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/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/users.py b/app/api/users.py new file mode 100644 index 0000000..d4714d3 --- /dev/null +++ b/app/api/users.py @@ -0,0 +1,54 @@ +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 import schemas +from app.models.user import User + +router = APIRouter() + +@router.post("/", response_model=schemas.User) +def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): + db_user = db.query(User).filter(User.email == user.email).first() + if db_user: + raise HTTPException(status_code=400, detail="Email already registered") + db_user = User(**user.dict()) + db.add(db_user) + db.commit() + db.refresh(db_user) + return db_user + +@router.get("/{user_id}", response_model=schemas.User) +def read_user(user_id: int, db: Session = Depends(get_db)): + db_user = db.query(User).filter(User.id == user_id).first() + if db_user is None: + raise HTTPException(status_code=404, detail="User not found") + return db_user + +@router.get("/", response_model=List[schemas.User]) +def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): + users = db.query(User).offset(skip).limit(limit).all() + return users + +@router.put("/{user_id}", response_model=schemas.User) +def update_user(user_id: int, user: schemas.UserUpdate, db: Session = Depends(get_db)): + db_user = db.query(User).filter(User.id == user_id).first() + if db_user is None: + raise HTTPException(status_code=404, detail="User not found") + + update_data = user.dict(exclude_unset=True) + for field, value in update_data.items(): + setattr(db_user, field, value) + + db.commit() + db.refresh(db_user) + return db_user + +@router.delete("/{user_id}") +def delete_user(user_id: int, db: Session = Depends(get_db)): + db_user = db.query(User).filter(User.id == user_id).first() + if db_user is None: + raise HTTPException(status_code=404, detail="User not found") + db.delete(db_user) + db.commit() + return {"message": "User deleted successfully"} \ 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..2677e30 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,26 @@ +from pathlib import Path +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from app.db.base import Base + +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() + +def create_tables(): + Base.metadata.create_all(bind=engine) \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/models/schemas.py b/app/models/schemas.py new file mode 100644 index 0000000..dba925e --- /dev/null +++ b/app/models/schemas.py @@ -0,0 +1,24 @@ +from pydantic import BaseModel +from datetime import datetime +from typing import Optional + +class UserBase(BaseModel): + email: str + name: str + is_active: bool = True + +class UserCreate(UserBase): + pass + +class UserUpdate(BaseModel): + email: Optional[str] = None + name: Optional[str] = None + is_active: Optional[bool] = None + +class User(UserBase): + id: int + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..b366b24 --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,13 @@ +from sqlalchemy import Column, Integer, String, DateTime, Boolean +from sqlalchemy.sql import func +from app.db.base import Base + +class User(Base): + __tablename__ = "users" + + id = Column(Integer, primary_key=True, index=True) + email = Column(String, unique=True, index=True, nullable=False) + name = Column(String, nullable=False) + 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()) \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..b1272e1 --- /dev/null +++ b/main.py @@ -0,0 +1,41 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +import uvicorn +from app.api.users import router as users_router +from app.db.session import create_tables + +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=["*"], +) + +app.include_router(users_router, prefix="/api/v1/users", tags=["users"]) + +@app.on_event("startup") +async def startup_event(): + create_tables() + +@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"} + +if __name__ == "__main__": + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..98f9e19 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +fastapi==0.104.1 +uvicorn[standard]==0.24.0 +sqlalchemy==2.0.23 +alembic==1.12.1 +pydantic==2.5.0 +python-multipart==0.0.6 +ruff==0.1.6 \ No newline at end of file