diff --git a/README.md b/README.md index e8acfba..f4e36fc 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,84 @@ -# 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 + +- User management (CRUD operations) +- Item management with user ownership +- SQLite database with Alembic migrations +- Automatic API documentation with FastAPI +- CORS enabled for all origins +- Health check endpoint + +## Project Structure + +``` +├── main.py # FastAPI application entry point +├── requirements.txt # Python dependencies +├── alembic.ini # Alembic configuration +├── alembic/ # Database migrations +├── app/ +│ ├── api/ # API routes +│ ├── crud/ # Database operations +│ ├── db/ # Database configuration +│ ├── models/ # SQLAlchemy models +│ └── schemas/ # Pydantic schemas +└── storage/ # Application storage directory +``` + +## Installation + +1. Install dependencies: +```bash +pip install -r requirements.txt +``` + +2. Run database migrations: +```bash +alembic upgrade head +``` + +3. Start the application: +```bash +uvicorn main:app --reload +``` + +## API Endpoints + +- **GET /**: Service information and links +- **GET /health**: Health check endpoint +- **GET /docs**: Interactive API documentation +- **GET /redoc**: Alternative API documentation + +### Users +- **POST /api/v1/users/**: Create a new user +- **GET /api/v1/users/**: List all users +- **GET /api/v1/users/{user_id}**: Get user by ID +- **PUT /api/v1/users/{user_id}**: Update user +- **DELETE /api/v1/users/{user_id}**: Delete user + +### Items +- **POST /api/v1/items/**: Create a new item +- **GET /api/v1/items/**: List all items +- **GET /api/v1/items/{item_id}**: Get item by ID +- **PUT /api/v1/items/{item_id}**: Update item +- **DELETE /api/v1/items/{item_id}**: Delete item +- **GET /api/v1/items/users/{user_id}/items**: Get items by user + +## Database + +The application uses SQLite as the database, stored at `/app/storage/db/db.sqlite`. + +## Environment Variables + +No environment variables are currently required for basic operation. + +## Development + +The application includes: +- Automatic code formatting with Ruff +- Database migrations with Alembic +- Comprehensive CRUD operations +- Input validation with Pydantic +- Automatic API documentation 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..8d80eff --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,53 @@ +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.insert(0, os.path.dirname(os.path.dirname(__file__))) + +from app.db.base import Base +from app.models.user import User # noqa: F401 +from app.models.item import Item # noqa: F401 + +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..11ad591 --- /dev/null +++ b/alembic/versions/001_initial_migration.py @@ -0,0 +1,55 @@ +"""Initial migration + +Revision ID: 001 +Revises: +Create Date: 2024-01-01 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: + # 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('full_name', 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_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=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.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/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/api_v1/__init__.py b/app/api/api_v1/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/api_v1/api.py b/app/api/api_v1/api.py new file mode 100644 index 0000000..8a6b4a1 --- /dev/null +++ b/app/api/api_v1/api.py @@ -0,0 +1,6 @@ +from fastapi import APIRouter +from app.api.api_v1.endpoints import users, items + +api_router = APIRouter() +api_router.include_router(users.router, prefix="/users", tags=["users"]) +api_router.include_router(items.router, prefix="/items", tags=["items"]) \ No newline at end of file diff --git a/app/api/api_v1/endpoints/__init__.py b/app/api/api_v1/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/api_v1/endpoints/items.py b/app/api/api_v1/endpoints/items.py new file mode 100644 index 0000000..57c1606 --- /dev/null +++ b/app/api/api_v1/endpoints/items.py @@ -0,0 +1,75 @@ +from typing import Any, List +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from app import crud, schemas +from app.db.session import get_db + +router = APIRouter() + +@router.get("/", response_model=List[schemas.Item]) +def read_items( + db: Session = Depends(get_db), + skip: int = 0, + limit: int = 100, +) -> Any: + items = crud.item.get_multi(db, skip=skip, limit=limit) + return items + +@router.post("/", response_model=schemas.Item) +def create_item( + *, + db: Session = Depends(get_db), + item_in: schemas.ItemCreate, + owner_id: int, +) -> Any: + item = crud.item.create_with_owner(db, obj_in=item_in, owner_id=owner_id) + return item + +@router.get("/{item_id}", response_model=schemas.Item) +def read_item( + *, + db: Session = Depends(get_db), + item_id: int, +) -> Any: + item = crud.item.get(db, id=item_id) + if not item: + raise HTTPException(status_code=404, detail="Item not found") + return item + +@router.put("/{item_id}", response_model=schemas.Item) +def update_item( + *, + db: Session = Depends(get_db), + item_id: int, + item_in: schemas.ItemUpdate, +) -> Any: + item = crud.item.get(db, id=item_id) + if not item: + raise HTTPException(status_code=404, detail="Item not found") + item = crud.item.update(db, db_obj=item, obj_in=item_in) + return item + +@router.delete("/{item_id}") +def delete_item( + *, + db: Session = Depends(get_db), + item_id: int, +) -> Any: + item = crud.item.get(db, id=item_id) + if not item: + raise HTTPException(status_code=404, detail="Item not found") + item = crud.item.remove(db, id=item_id) + return {"message": "Item deleted successfully"} + +@router.get("/users/{user_id}/items", response_model=List[schemas.Item]) +def read_user_items( + *, + db: Session = Depends(get_db), + user_id: int, + skip: int = 0, + limit: int = 100, +) -> Any: + items = crud.item.get_multi_by_owner( + db, owner_id=user_id, skip=skip, limit=limit + ) + return items \ No newline at end of file diff --git a/app/api/api_v1/endpoints/users.py b/app/api/api_v1/endpoints/users.py new file mode 100644 index 0000000..ebb6a36 --- /dev/null +++ b/app/api/api_v1/endpoints/users.py @@ -0,0 +1,67 @@ +from typing import Any, List +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from app import crud, schemas +from app.db.session import get_db + +router = APIRouter() + +@router.post("/", response_model=schemas.User) +def create_user( + *, + db: Session = Depends(get_db), + user_in: schemas.UserCreate, +) -> Any: + user = crud.user.get_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=400, + detail="The user with this email already exists in the system.", + ) + user = crud.user.create(db, obj_in=user_in) + return user + +@router.get("/", response_model=List[schemas.User]) +def read_users( + db: Session = Depends(get_db), + skip: int = 0, + limit: int = 100, +) -> Any: + users = crud.user.get_multi(db, skip=skip, limit=limit) + return users + +@router.get("/{user_id}", response_model=schemas.User) +def read_user( + *, + db: Session = Depends(get_db), + user_id: int, +) -> Any: + user = crud.user.get(db, id=user_id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + return user + +@router.put("/{user_id}", response_model=schemas.User) +def update_user( + *, + db: Session = Depends(get_db), + user_id: int, + user_in: schemas.UserUpdate, +) -> Any: + user = crud.user.get(db, id=user_id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + user = crud.user.update(db, db_obj=user, obj_in=user_in) + return user + +@router.delete("/{user_id}") +def delete_user( + *, + db: Session = Depends(get_db), + user_id: int, +) -> Any: + user = crud.user.get(db, id=user_id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + user = crud.user.remove(db, id=user_id) + return {"message": "User deleted successfully"} \ No newline at end of file diff --git a/app/crud/__init__.py b/app/crud/__init__.py new file mode 100644 index 0000000..ef8847c --- /dev/null +++ b/app/crud/__init__.py @@ -0,0 +1,4 @@ +from .user import user +from .item import item + +__all__ = ["user", "item"] \ No newline at end of file diff --git a/app/crud/base.py b/app/crud/base.py new file mode 100644 index 0000000..478b886 --- /dev/null +++ b/app/crud/base.py @@ -0,0 +1,52 @@ +from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union +from pydantic import BaseModel +from sqlalchemy.orm import Session +from app.db.base import Base + +ModelType = TypeVar("ModelType", bound=Base) +CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) +UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) + +class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): + def __init__(self, model: Type[ModelType]): + self.model = model + + def get(self, db: Session, id: Any) -> Optional[ModelType]: + return db.query(self.model).filter(self.model.id == id).first() + + def get_multi( + self, db: Session, *, skip: int = 0, limit: int = 100 + ) -> List[ModelType]: + return db.query(self.model).offset(skip).limit(limit).all() + + def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType: + obj_in_data = obj_in.dict() + db_obj = self.model(**obj_in_data) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def update( + self, + db: Session, + *, + db_obj: ModelType, + obj_in: Union[UpdateSchemaType, Dict[str, Any]] + ) -> ModelType: + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + for field, value in update_data.items(): + setattr(db_obj, field, value) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def remove(self, db: Session, *, id: int) -> ModelType: + obj = db.query(self.model).get(id) + db.delete(obj) + db.commit() + return obj \ No newline at end of file diff --git a/app/crud/item.py b/app/crud/item.py new file mode 100644 index 0000000..9d10172 --- /dev/null +++ b/app/crud/item.py @@ -0,0 +1,29 @@ +from typing import List +from sqlalchemy.orm import Session +from app.crud.base import CRUDBase +from app.models.item import Item +from app.schemas.item import ItemCreate, ItemUpdate + +class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]): + def create_with_owner( + self, db: Session, *, obj_in: ItemCreate, owner_id: int + ) -> Item: + obj_in_data = obj_in.dict() + db_obj = self.model(**obj_in_data, owner_id=owner_id) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def get_multi_by_owner( + self, db: Session, *, owner_id: int, skip: int = 0, limit: int = 100 + ) -> List[Item]: + return ( + db.query(self.model) + .filter(Item.owner_id == owner_id) + .offset(skip) + .limit(limit) + .all() + ) + +item = CRUDItem(Item) \ No newline at end of file diff --git a/app/crud/user.py b/app/crud/user.py new file mode 100644 index 0000000..c5c828d --- /dev/null +++ b/app/crud/user.py @@ -0,0 +1,38 @@ +from typing import Optional +from sqlalchemy.orm import Session +from passlib.context import CryptContext +from app.crud.base import CRUDBase +from app.models.user import User +from app.schemas.user import UserCreate, UserUpdate + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + +class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]): + def get_by_email(self, db: Session, *, email: str) -> Optional[User]: + return db.query(User).filter(User.email == email).first() + + def create(self, db: Session, *, obj_in: UserCreate) -> User: + hashed_password = pwd_context.hash(obj_in.password) + db_obj = User( + email=obj_in.email, + hashed_password=hashed_password, + full_name=obj_in.full_name, + is_active=obj_in.is_active, + ) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def authenticate(self, db: Session, *, email: str, password: str) -> Optional[User]: + user = self.get_by_email(db, email=email) + if not user: + return None + if not pwd_context.verify(password, user.hashed_password): + return None + return user + + def is_active(self, user: User) -> bool: + return user.is_active + +user = CRUDUser(User) \ 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..b6f41f1 --- /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..d7cc71b --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,4 @@ +from .user import User +from .item import Item + +__all__ = ["User", "Item"] \ No newline at end of file diff --git a/app/models/item.py b/app/models/item.py new file mode 100644 index 0000000..87f98be --- /dev/null +++ b/app/models/item.py @@ -0,0 +1,16 @@ +from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey +from sqlalchemy.sql import func +from sqlalchemy.orm import relationship +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")) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), onupdate=func.now()) + + 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..88dc61e --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,17 @@ +from sqlalchemy import Column, Integer, String, Boolean, DateTime +from sqlalchemy.sql import func +from sqlalchemy.orm import relationship +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) + full_name = 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()) + + items = relationship("Item", back_populates="owner") \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..1e3a879 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,4 @@ +from .user import User, UserCreate, UserUpdate +from .item import Item, ItemCreate, ItemUpdate + +__all__ = ["User", "UserCreate", "UserUpdate", "Item", "ItemCreate", "ItemUpdate"] \ No newline at end of file diff --git a/app/schemas/item.py b/app/schemas/item.py new file mode 100644 index 0000000..c8d9ebf --- /dev/null +++ b/app/schemas/item.py @@ -0,0 +1,23 @@ +from typing import Optional +from pydantic import BaseModel +from datetime import datetime + +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: Optional[datetime] = None + + 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..b7ef925 --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,25 @@ +from typing import Optional +from pydantic import BaseModel +from datetime import datetime + +class UserBase(BaseModel): + email: str + full_name: Optional[str] = None + is_active: bool = True + +class UserCreate(UserBase): + password: str + +class UserUpdate(BaseModel): + email: Optional[str] = None + full_name: Optional[str] = None + is_active: Optional[bool] = None + password: Optional[str] = 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/main.py b/main.py new file mode 100644 index 0000000..80488fe --- /dev/null +++ b/main.py @@ -0,0 +1,47 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.api.api_v1.api import api_router +from app.db.session import engine +from app.db.base import Base + +# Create database tables +Base.metadata.create_all(bind=engine) + +app = FastAPI( + title="REST API Service", + description="A comprehensive REST API built with FastAPI", + version="1.0.0", + openapi_url="/openapi.json", + docs_url="/docs", + redoc_url="/redoc" +) + +# Configure CORS +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Include API routes +app.include_router(api_router, prefix="/api/v1") + +@app.get("/") +async def root(): + return { + "title": "REST API Service", + "description": "A comprehensive REST API built with FastAPI", + "documentation": "/docs", + "health_check": "/health" + } + +@app.get("/health") +async def health_check(): + return { + "status": "healthy", + "service": "REST API Service", + "version": "1.0.0" + } \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..828fae5 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +fastapi==0.104.1 +uvicorn==0.24.0 +sqlalchemy==2.0.23 +alembic==1.12.1 +pydantic==2.5.0 +python-multipart==0.0.6 +passlib==1.7.4 +python-jose==3.3.0 +bcrypt==4.1.2 +ruff==0.1.6 \ No newline at end of file