From 10f64177dcde0328c00e7d8ea439ccac1f25b2f8 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Thu, 17 Jul 2025 16:54:25 +0000 Subject: [PATCH] Create REST API with FastAPI and SQLite - Set up FastAPI application with CORS and authentication - Implement user registration and login with JWT tokens - Create SQLAlchemy models for users and items - Add CRUD endpoints for item management - Configure Alembic for database migrations - Add health check endpoint - Include comprehensive API documentation - Set up proper project structure with routers and schemas --- README.md | 68 +++++++++++++++++++- alembic.ini | 41 ++++++++++++ alembic/env.py | 51 +++++++++++++++ alembic/script.py.mako | 24 +++++++ alembic/versions/001_initial_migration.py | 52 ++++++++++++++++ app/__init__.py | 0 app/core/__init__.py | 0 app/core/auth.py | 43 +++++++++++++ app/core/config.py | 12 ++++ app/db/__init__.py | 0 app/db/base.py | 3 + app/db/session.py | 22 +++++++ app/models/__init__.py | 0 app/models/item.py | 16 +++++ app/models/user.py | 15 +++++ app/routers/__init__.py | 0 app/routers/auth.py | 72 +++++++++++++++++++++ app/routers/health.py | 27 ++++++++ app/routers/items.py | 76 +++++++++++++++++++++++ app/schemas/__init__.py | 0 app/schemas/item.py | 23 +++++++ app/schemas/user.py | 28 +++++++++ main.py | 47 ++++++++++++++ requirements.txt | 9 +++ 24 files changed, 627 insertions(+), 2 deletions(-) create mode 100644 alembic.ini create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 alembic/versions/001_initial_migration.py create mode 100644 app/__init__.py create mode 100644 app/core/__init__.py create mode 100644 app/core/auth.py create mode 100644 app/core/config.py create mode 100644 app/db/__init__.py create mode 100644 app/db/base.py create mode 100644 app/db/session.py create mode 100644 app/models/__init__.py create mode 100644 app/models/item.py create mode 100644 app/models/user.py create mode 100644 app/routers/__init__.py create mode 100644 app/routers/auth.py create mode 100644 app/routers/health.py create mode 100644 app/routers/items.py create mode 100644 app/schemas/__init__.py create mode 100644 app/schemas/item.py create mode 100644 app/schemas/user.py create mode 100644 main.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..719abc1 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,67 @@ -# 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 and SQLite, featuring user authentication, CRUD operations, and health monitoring. + +## Features + +- User registration and authentication with JWT tokens +- Item management (CRUD operations) +- SQLite database with SQLAlchemy ORM +- Database migrations with Alembic +- Health check endpoint +- CORS enabled for all origins +- Interactive API documentation at `/docs` and `/redoc` +- OpenAPI specification at `/openapi.json` + +## Installation + +1. Install dependencies: +```bash +pip install -r requirements.txt +``` + +2. Run the application: +```bash +uvicorn main:app --host 0.0.0.0 --port 8000 +``` + +## Environment Variables + +Set the following environment variables: + +- `SECRET_KEY`: JWT secret key for token signing (required for production) + +## API Endpoints + +### Authentication +- `POST /auth/register` - Register a new user +- `POST /auth/login` - Login and get access token +- `GET /auth/me` - Get current user profile + +### Items +- `GET /items/` - List user's items +- `POST /items/` - Create a new item +- `GET /items/{item_id}` - Get a specific item +- `PUT /items/{item_id}` - Update an item +- `DELETE /items/{item_id}` - Delete an item + +### Health +- `GET /health` - Health check endpoint + +### Documentation +- `GET /` - Service information +- `GET /docs` - Interactive API documentation +- `GET /redoc` - ReDoc documentation +- `GET /openapi.json` - OpenAPI specification + +## Database + +The application uses SQLite with database file stored at `/app/storage/db/db.sqlite`. + +## Development + +The application includes Ruff for code linting and formatting. Run linting with: +```bash +ruff check . +ruff format . +``` 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..b22a8d6 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,51 @@ +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_initial_migration.py b/alembic/versions/001_initial_migration.py new file mode 100644 index 0000000..82986be --- /dev/null +++ b/alembic/versions/001_initial_migration.py @@ -0,0 +1,52 @@ +"""Initial migration + +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: + # Create users table + op.create_table('users', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('email', sa.String(), nullable=False), + sa.Column('hashed_password', sa.String(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), 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) + + # Create items table + op.create_table('items', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('owner_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ), + 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() -> None: + 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') + 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/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/auth.py b/app/core/auth.py new file mode 100644 index 0000000..06622a3 --- /dev/null +++ b/app/core/auth.py @@ -0,0 +1,43 @@ +from datetime import datetime, timedelta +from typing import Optional +from jose import JWTError, jwt +from passlib.context import CryptContext +from fastapi import HTTPException, status +from app.core.config import settings + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + +def verify_password(plain_password: str, hashed_password: str) -> bool: + return pwd_context.verify(plain_password, hashed_password) + +def get_password_hash(password: str) -> str: + return pwd_context.hash(password) + +def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): + to_encode = data.copy() + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta(minutes=settings.access_token_expire_minutes) + + to_encode.update({"exp": expire}) + encoded_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm) + return encoded_jwt + +def verify_token(token: str) -> Optional[str]: + try: + payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm]) + email: str = payload.get("sub") + if email is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + return email + except JWTError: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) \ No newline at end of file diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..aae34cb --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,12 @@ +import os +from pydantic import BaseSettings + +class Settings(BaseSettings): + secret_key: str = os.getenv("SECRET_KEY", "your-secret-key-here") + algorithm: str = "HS256" + access_token_expire_minutes: int = 30 + + class Config: + env_file = ".env" + +settings = Settings() \ 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..3abef45 --- /dev/null +++ b/app/db/session.py @@ -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() \ 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/item.py b/app/models/item.py new file mode 100644 index 0000000..f146adf --- /dev/null +++ b/app/models/item.py @@ -0,0 +1,16 @@ +from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime +from sqlalchemy.orm import relationship +from datetime import datetime +from app.db.base import Base + +class Item(Base): + __tablename__ = "items" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String, index=True, nullable=False) + description = Column(Text, nullable=True) + owner_id = Column(Integer, ForeignKey("users.id"), nullable=False) + created_at = Column(DateTime, default=datetime.utcnow) + updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) + + owner = relationship("User", back_populates="items") \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..b1cabaf --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,15 @@ +from sqlalchemy import Column, Integer, String, Boolean, DateTime +from sqlalchemy.orm import relationship +from datetime import datetime +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) + hashed_password = Column(String, nullable=False) + is_active = Column(Boolean, default=True) + created_at = Column(DateTime, default=datetime.utcnow) + + items = relationship("Item", back_populates="owner") \ No newline at end of file diff --git a/app/routers/__init__.py b/app/routers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/routers/auth.py b/app/routers/auth.py new file mode 100644 index 0000000..3e53fab --- /dev/null +++ b/app/routers/auth.py @@ -0,0 +1,72 @@ +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from sqlalchemy.orm import Session +from datetime import timedelta + +from app.db.session import get_db +from app.models.user import User +from app.schemas.user import UserCreate, UserLogin, Token, User as UserSchema +from app.core.auth import verify_password, get_password_hash, create_access_token, verify_token +from app.core.config import settings + +router = APIRouter() +security = HTTPBearer() + +def get_user_by_email(db: Session, email: str): + return db.query(User).filter(User.email == email).first() + +def create_user(db: Session, user: UserCreate): + hashed_password = get_password_hash(user.password) + db_user = User(email=user.email, hashed_password=hashed_password) + db.add(db_user) + db.commit() + db.refresh(db_user) + return db_user + +def authenticate_user(db: Session, email: str, password: str): + user = get_user_by_email(db, email) + if not user: + return False + if not verify_password(password, user.hashed_password): + return False + return user + +def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db)): + email = verify_token(credentials.credentials) + user = get_user_by_email(db, email) + if user is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + return user + +@router.post("/register", response_model=UserSchema) +def register(user: UserCreate, db: Session = Depends(get_db)): + db_user = get_user_by_email(db, user.email) + if db_user: + raise HTTPException( + status_code=400, + detail="Email already registered" + ) + return create_user(db, user) + +@router.post("/login", response_model=Token) +def login(user_credentials: UserLogin, db: Session = Depends(get_db)): + user = authenticate_user(db, user_credentials.email, user_credentials.password) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect email or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + access_token_expires = timedelta(minutes=settings.access_token_expire_minutes) + access_token = create_access_token( + data={"sub": user.email}, expires_delta=access_token_expires + ) + return {"access_token": access_token, "token_type": "bearer"} + +@router.get("/me", response_model=UserSchema) +def read_users_me(current_user: User = Depends(get_current_user)): + return current_user \ No newline at end of file diff --git a/app/routers/health.py b/app/routers/health.py new file mode 100644 index 0000000..4175e20 --- /dev/null +++ b/app/routers/health.py @@ -0,0 +1,27 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session +from sqlalchemy import text +from app.db.session import get_db +import os + +router = APIRouter() + +@router.get("/health") +def health_check(db: Session = Depends(get_db)): + try: + # Check database connectivity + db.execute(text("SELECT 1")) + db_status = "healthy" + except Exception as e: + db_status = f"unhealthy: {str(e)}" + + # Check if storage directory exists + storage_path = "/app/storage" + storage_status = "healthy" if os.path.exists(storage_path) else "storage directory not found" + + return { + "status": "healthy" if db_status == "healthy" and storage_status == "healthy" else "unhealthy", + "database": db_status, + "storage": storage_status, + "service": "REST API Service" + } \ No newline at end of file diff --git a/app/routers/items.py b/app/routers/items.py new file mode 100644 index 0000000..a0b2d15 --- /dev/null +++ b/app/routers/items.py @@ -0,0 +1,76 @@ +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.models.user import User +from app.schemas.item import ItemCreate, ItemUpdate, Item as ItemSchema +from app.routers.auth import get_current_user + +router = APIRouter() + +def get_items(db: Session, user_id: int, skip: int = 0, limit: int = 100): + return db.query(Item).filter(Item.owner_id == user_id).offset(skip).limit(limit).all() + +def get_item(db: Session, item_id: int, user_id: int): + return db.query(Item).filter(Item.id == item_id, Item.owner_id == user_id).first() + +def create_item(db: Session, item: ItemCreate, user_id: int): + db_item = Item(**item.dict(), owner_id=user_id) + db.add(db_item) + db.commit() + db.refresh(db_item) + return db_item + +def update_item(db: Session, item_id: int, item_update: ItemUpdate, user_id: int): + db_item = db.query(Item).filter(Item.id == item_id, Item.owner_id == user_id).first() + if not db_item: + return None + + 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 + +def delete_item(db: Session, item_id: int, user_id: int): + db_item = db.query(Item).filter(Item.id == item_id, Item.owner_id == user_id).first() + if not db_item: + return None + + db.delete(db_item) + db.commit() + return db_item + +@router.get("/", response_model=List[ItemSchema]) +def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): + items = get_items(db, current_user.id, skip=skip, limit=limit) + return items + +@router.post("/", response_model=ItemSchema) +def create_item_endpoint(item: ItemCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): + return create_item(db, item, current_user.id) + +@router.get("/{item_id}", response_model=ItemSchema) +def read_item(item_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): + db_item = get_item(db, item_id, current_user.id) + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + return db_item + +@router.put("/{item_id}", response_model=ItemSchema) +def update_item_endpoint(item_id: int, item_update: ItemUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): + db_item = update_item(db, item_id, item_update, current_user.id) + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + return db_item + +@router.delete("/{item_id}", response_model=ItemSchema) +def delete_item_endpoint(item_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): + db_item = delete_item(db, item_id, current_user.id) + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + return db_item \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/schemas/item.py b/app/schemas/item.py new file mode 100644 index 0000000..19ce246 --- /dev/null +++ b/app/schemas/item.py @@ -0,0 +1,23 @@ +from pydantic import BaseModel +from datetime import datetime +from typing import Optional + +class ItemBase(BaseModel): + title: str + description: Optional[str] = None + +class ItemCreate(ItemBase): + pass + +class ItemUpdate(BaseModel): + title: Optional[str] = None + description: Optional[str] = None + +class Item(ItemBase): + id: int + owner_id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True \ No newline at end of file diff --git a/app/schemas/user.py b/app/schemas/user.py new file mode 100644 index 0000000..2ac0a69 --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,28 @@ +from pydantic import BaseModel, EmailStr +from datetime import datetime +from typing import Optional + +class UserBase(BaseModel): + email: EmailStr + +class UserCreate(UserBase): + password: str + +class UserLogin(BaseModel): + email: EmailStr + password: str + +class User(UserBase): + id: int + is_active: bool + created_at: datetime + + class Config: + from_attributes = True + +class Token(BaseModel): + access_token: str + token_type: str + +class TokenData(BaseModel): + email: Optional[str] = None \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..daceaee --- /dev/null +++ b/main.py @@ -0,0 +1,47 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from contextlib import asynccontextmanager + +from app.db.session import engine +from app.db.base import Base +from app.routers import auth, items, health + +@asynccontextmanager +async def lifespan(app: FastAPI): + # Create database tables + Base.metadata.create_all(bind=engine) + yield + +app = FastAPI( + title="REST API Service", + description="A comprehensive REST API built with FastAPI and SQLite", + version="1.0.0", + lifespan=lifespan, + openapi_url="/openapi.json" +) + +# Add CORS middleware +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Include routers +app.include_router(auth.router, prefix="/auth", tags=["authentication"]) +app.include_router(items.router, prefix="/items", tags=["items"]) +app.include_router(health.router, tags=["health"]) + +@app.get("/") +async def root(): + return { + "title": "REST API Service", + "documentation": "/docs", + "health_check": "/health" + } + +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..74941b6 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +fastapi==0.104.1 +uvicorn==0.24.0 +sqlalchemy==2.0.23 +alembic==1.13.0 +pydantic==2.5.0 +python-multipart==0.0.6 +passlib[bcrypt]==1.7.4 +python-jose[cryptography]==3.3.0 +ruff==0.1.6 \ No newline at end of file