diff --git a/README.md b/README.md index e8acfba..2de5a22 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,173 @@ -# FastAPI Application +# Task Manager API -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A comprehensive Task Manager API built with FastAPI and SQLite, providing full CRUD operations for task management with filtering, search, and statistics capabilities. + +## Features + +- ✅ **Task Management**: Create, read, update, and delete tasks +- 🔍 **Advanced Filtering**: Filter tasks by status, priority, and search text +- 📊 **Statistics**: Get task count summaries by status +- 🚀 **FastAPI Framework**: Modern, fast web framework with automatic API documentation +- 💾 **SQLite Database**: Lightweight, serverless database with Alembic migrations +- 📝 **Comprehensive API Documentation**: Auto-generated OpenAPI/Swagger docs +- 🌐 **CORS Support**: Cross-origin resource sharing enabled +- ⚡ **Health Checks**: Built-in health monitoring endpoint + +## Task Properties + +Each task includes: +- **Title**: Task name (required, max 255 characters) +- **Description**: Optional detailed description +- **Status**: `pending`, `in_progress`, or `completed` +- **Priority**: `low`, `medium`, or `high` +- **Due Date**: Optional deadline +- **Timestamps**: Auto-generated creation and update times + +## API Endpoints + +### Tasks +- `GET /tasks/` - List all tasks with optional filtering +- `POST /tasks/` - Create a new task +- `GET /tasks/{id}` - Get a specific task +- `PUT /tasks/{id}` - Update a task +- `DELETE /tasks/{id}` - Delete a task +- `GET /tasks/stats/summary` - Get task statistics + +### System +- `GET /` - API information and links +- `GET /health` - Health check endpoint +- `GET /docs` - Interactive API documentation (Swagger UI) +- `GET /redoc` - Alternative API documentation +- `GET /openapi.json` - OpenAPI schema + +## Quick Start + +1. **Install Dependencies** + ```bash + pip install -r requirements.txt + ``` + +2. **Run Database Migrations** + ```bash + alembic upgrade head + ``` + +3. **Start the Server** + ```bash + uvicorn main:app --reload + ``` + +4. **Access the Application** + - API: http://localhost:8000 + - Documentation: http://localhost:8000/docs + - Health Check: http://localhost:8000/health + +## API Usage Examples + +### Create a Task +```bash +curl -X POST "http://localhost:8000/tasks/" \ + -H "Content-Type: application/json" \ + -d '{ + "title": "Complete project documentation", + "description": "Write comprehensive README and API docs", + "priority": "high", + "status": "pending" + }' +``` + +### Get All Tasks +```bash +curl "http://localhost:8000/tasks/" +``` + +### Filter Tasks +```bash +# Get high priority tasks +curl "http://localhost:8000/tasks/?priority=high" + +# Get completed tasks +curl "http://localhost:8000/tasks/?status=completed" + +# Search tasks +curl "http://localhost:8000/tasks/?search=documentation" +``` + +### Update a Task +```bash +curl -X PUT "http://localhost:8000/tasks/1" \ + -H "Content-Type: application/json" \ + -d '{ + "status": "completed" + }' +``` + +### Get Task Statistics +```bash +curl "http://localhost:8000/tasks/stats/summary" +``` + +## Database + +The application uses SQLite with the following configuration: +- **Database Location**: `/app/storage/db/db.sqlite` +- **Migration Tool**: Alembic +- **Schema Management**: Automatic table creation and migrations + +## Environment Variables + +Currently, no environment variables are required. The application uses SQLite with a fixed path for simplicity. + +## Project Structure + +``` +/ +├── main.py # FastAPI application entry point +├── requirements.txt # Python dependencies +├── alembic.ini # Alembic configuration +├── alembic/ # Database migrations +│ ├── env.py +│ └── versions/ +├── app/ +│ ├── api/ +│ │ └── tasks.py # Task API routes +│ ├── crud/ +│ │ └── task.py # Database operations +│ ├── db/ +│ │ ├── base.py # SQLAlchemy base +│ │ └── session.py # Database connection +│ ├── models/ +│ │ └── task.py # Database models +│ └── schemas/ +│ └── task.py # Pydantic schemas +└── storage/ + └── db/ # SQLite database files +``` + +## Development Commands + +```bash +# Install dependencies +pip install -r requirements.txt + +# Run migrations +alembic upgrade head + +# Start development server +uvicorn main:app --reload --host 0.0.0.0 --port 8000 + +# Run linting +python -m ruff check . --fix +``` + +## Technologies Used + +- **FastAPI**: Modern Python web framework +- **SQLAlchemy**: SQL toolkit and ORM +- **Alembic**: Database migration tool +- **Pydantic**: Data validation using Python type hints +- **SQLite**: Lightweight database +- **Uvicorn**: ASGI server +- **Ruff**: Fast Python linter + +Built with BackendIM - AI-powered backend development assistant. 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..861bdf2 --- /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 os +import sys + +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from app.db.base import Base +from app.models.task import Task + +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_tasks_table.py b/alembic/versions/001_create_tasks_table.py new file mode 100644 index 0000000..a768cbb --- /dev/null +++ b/alembic/versions/001_create_tasks_table.py @@ -0,0 +1,37 @@ +"""create tasks 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('tasks', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(length=255), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('status', sa.Enum('PENDING', 'IN_PROGRESS', 'COMPLETED', name='taskstatus'), nullable=False), + sa.Column('priority', sa.Enum('LOW', 'MEDIUM', 'HIGH', name='taskpriority'), nullable=False), + sa.Column('due_date', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_tasks_id'), 'tasks', ['id'], unique=False) + op.create_index(op.f('ix_tasks_title'), 'tasks', ['title'], unique=False) + + +def downgrade() -> None: + op.drop_index(op.f('ix_tasks_title'), table_name='tasks') + op.drop_index(op.f('ix_tasks_id'), table_name='tasks') + op.drop_table('tasks') \ No newline at end of file diff --git a/app/api/tasks.py b/app/api/tasks.py new file mode 100644 index 0000000..f6c27f5 --- /dev/null +++ b/app/api/tasks.py @@ -0,0 +1,73 @@ +from fastapi import APIRouter, Depends, HTTPException, Query +from sqlalchemy.orm import Session +from typing import List, Optional +from app.crud import task as crud_task +from app.schemas.task import TaskCreate, TaskUpdate, TaskResponse +from app.models.task import TaskStatus, TaskPriority +from app.db.session import get_db + +router = APIRouter() + + +@router.get("/", response_model=List[TaskResponse]) +def read_tasks( + skip: int = Query(0, ge=0, description="Number of tasks to skip"), + limit: int = Query(100, ge=1, le=1000, description="Maximum number of tasks to return"), + status: Optional[TaskStatus] = Query(None, description="Filter by task status"), + priority: Optional[TaskPriority] = Query(None, description="Filter by task priority"), + search: Optional[str] = Query(None, description="Search in title and description"), + db: Session = Depends(get_db) +): + tasks = crud_task.get_tasks( + db=db, + skip=skip, + limit=limit, + status=status, + priority=priority, + search=search + ) + return tasks + + +@router.post("/", response_model=TaskResponse) +def create_task(task: TaskCreate, db: Session = Depends(get_db)): + return crud_task.create_task(db=db, task=task) + + +@router.get("/{task_id}", response_model=TaskResponse) +def read_task(task_id: int, db: Session = Depends(get_db)): + db_task = crud_task.get_task(db=db, task_id=task_id) + if db_task is None: + raise HTTPException(status_code=404, detail="Task not found") + return db_task + + +@router.put("/{task_id}", response_model=TaskResponse) +def update_task(task_id: int, task: TaskUpdate, db: Session = Depends(get_db)): + db_task = crud_task.update_task(db=db, task_id=task_id, task_update=task) + if db_task is None: + raise HTTPException(status_code=404, detail="Task not found") + return db_task + + +@router.delete("/{task_id}") +def delete_task(task_id: int, db: Session = Depends(get_db)): + success = crud_task.delete_task(db=db, task_id=task_id) + if not success: + raise HTTPException(status_code=404, detail="Task not found") + return {"message": "Task deleted successfully"} + + +@router.get("/stats/summary") +def get_task_stats(db: Session = Depends(get_db)): + total_tasks = crud_task.get_tasks_count(db=db) + pending_tasks = crud_task.get_tasks_by_status_count(db=db, status=TaskStatus.PENDING) + in_progress_tasks = crud_task.get_tasks_by_status_count(db=db, status=TaskStatus.IN_PROGRESS) + completed_tasks = crud_task.get_tasks_by_status_count(db=db, status=TaskStatus.COMPLETED) + + return { + "total_tasks": total_tasks, + "pending_tasks": pending_tasks, + "in_progress_tasks": in_progress_tasks, + "completed_tasks": completed_tasks + } \ No newline at end of file diff --git a/app/crud/task.py b/app/crud/task.py new file mode 100644 index 0000000..2bf57d3 --- /dev/null +++ b/app/crud/task.py @@ -0,0 +1,76 @@ +from sqlalchemy.orm import Session +from sqlalchemy import or_ +from typing import List, Optional +from app.models.task import Task, TaskStatus, TaskPriority +from app.schemas.task import TaskCreate, TaskUpdate + + +def get_task(db: Session, task_id: int) -> Optional[Task]: + return db.query(Task).filter(Task.id == task_id).first() + + +def get_tasks( + db: Session, + skip: int = 0, + limit: int = 100, + status: Optional[TaskStatus] = None, + priority: Optional[TaskPriority] = None, + search: Optional[str] = None +) -> List[Task]: + query = db.query(Task) + + if status: + query = query.filter(Task.status == status) + + if priority: + query = query.filter(Task.priority == priority) + + if search: + query = query.filter( + or_( + Task.title.contains(search), + Task.description.contains(search) + ) + ) + + return query.offset(skip).limit(limit).all() + + +def create_task(db: Session, task: TaskCreate) -> Task: + db_task = Task(**task.dict()) + db.add(db_task) + db.commit() + db.refresh(db_task) + return db_task + + +def update_task(db: Session, task_id: int, task_update: TaskUpdate) -> Optional[Task]: + db_task = db.query(Task).filter(Task.id == task_id).first() + if not db_task: + return None + + update_data = task_update.dict(exclude_unset=True) + for field, value in update_data.items(): + setattr(db_task, field, value) + + db.commit() + db.refresh(db_task) + return db_task + + +def delete_task(db: Session, task_id: int) -> bool: + db_task = db.query(Task).filter(Task.id == task_id).first() + if not db_task: + return False + + db.delete(db_task) + db.commit() + return True + + +def get_tasks_count(db: Session) -> int: + return db.query(Task).count() + + +def get_tasks_by_status_count(db: Session, status: TaskStatus) -> int: + return db.query(Task).filter(Task.status == status).count() \ No newline at end of file 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..97fa54e --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,23 @@ +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/task.py b/app/models/task.py new file mode 100644 index 0000000..d0d12bd --- /dev/null +++ b/app/models/task.py @@ -0,0 +1,29 @@ +from sqlalchemy import Column, Integer, String, DateTime, Enum, Text +from sqlalchemy.sql import func +import enum +from app.db.base import Base + + +class TaskStatus(str, enum.Enum): + PENDING = "pending" + IN_PROGRESS = "in_progress" + COMPLETED = "completed" + + +class TaskPriority(str, enum.Enum): + LOW = "low" + MEDIUM = "medium" + HIGH = "high" + + +class Task(Base): + __tablename__ = "tasks" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String(255), nullable=False, index=True) + description = Column(Text, nullable=True) + status = Column(Enum(TaskStatus), default=TaskStatus.PENDING, nullable=False) + priority = Column(Enum(TaskPriority), default=TaskPriority.MEDIUM, nullable=False) + due_date = Column(DateTime, nullable=True) + created_at = Column(DateTime, default=func.now(), nullable=False) + updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=False) \ No newline at end of file diff --git a/app/schemas/task.py b/app/schemas/task.py new file mode 100644 index 0000000..94352b7 --- /dev/null +++ b/app/schemas/task.py @@ -0,0 +1,33 @@ +from pydantic import BaseModel, Field +from datetime import datetime +from typing import Optional +from app.models.task import TaskStatus, TaskPriority + + +class TaskBase(BaseModel): + title: str = Field(..., min_length=1, max_length=255, description="Task title") + description: Optional[str] = Field(None, description="Task description") + status: TaskStatus = Field(TaskStatus.PENDING, description="Task status") + priority: TaskPriority = Field(TaskPriority.MEDIUM, description="Task priority") + due_date: Optional[datetime] = Field(None, description="Task due date") + + +class TaskCreate(TaskBase): + pass + + +class TaskUpdate(BaseModel): + title: Optional[str] = Field(None, min_length=1, max_length=255, description="Task title") + description: Optional[str] = Field(None, description="Task description") + status: Optional[TaskStatus] = Field(None, description="Task status") + priority: Optional[TaskPriority] = Field(None, description="Task priority") + due_date: Optional[datetime] = Field(None, description="Task due date") + + +class TaskResponse(TaskBase): + id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True \ No newline at end of file diff --git a/lint.py b/lint.py new file mode 100644 index 0000000..483a13f --- /dev/null +++ b/lint.py @@ -0,0 +1,12 @@ +import subprocess +import sys + +try: + result = subprocess.run([sys.executable, "-m", "ruff", "check", ".", "--fix"], + capture_output=True, text=True) + print("STDOUT:", result.stdout) + if result.stderr: + print("STDERR:", result.stderr) + print("Return code:", result.returncode) +except Exception as e: + print(f"Error running ruff: {e}") \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..462a4ac --- /dev/null +++ b/main.py @@ -0,0 +1,46 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from app.api import tasks +from app.db.session import engine +from app.db.base import Base + +app = FastAPI( + title="Task Manager API", + description="A comprehensive Task Manager API built with FastAPI", + version="1.0.0", + openapi_url="/openapi.json", + docs_url="/docs", + redoc_url="/redoc" +) + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +Base.metadata.create_all(bind=engine) + +app.include_router(tasks.router, prefix="/tasks", tags=["tasks"]) + + +@app.get("/") +def read_root(): + return { + "title": "Task Manager API", + "description": "A comprehensive Task Manager API built with FastAPI", + "version": "1.0.0", + "documentation": "/docs", + "health_check": "/health" + } + + +@app.get("/health") +def health_check(): + return { + "status": "healthy", + "service": "Task Manager API", + "version": "1.0.0" + } \ 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