diff --git a/README.md b/README.md index e8acfba..353ef88 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,158 @@ -# FastAPI Application +# Task Manager API -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A RESTful API for managing tasks built with FastAPI and SQLite. + +## Features + +- CRUD operations for tasks +- Task filtering by status +- Task pagination +- Automatic API documentation +- Health check endpoint + +## Project Structure + +``` +taskmanagerapi-daenmk/ +├── alembic.ini +├── app/ +│ ├── api/ +│ │ └── v1/ +│ │ ├── endpoints/ +│ │ │ └── tasks.py +│ │ └── router.py +│ ├── core/ +│ │ └── config.py +│ ├── database/ +│ │ ├── base.py +│ │ ├── base_class.py +│ │ ├── deps.py +│ │ └── session.py +│ ├── models/ +│ │ └── task.py +│ └── schemas/ +│ └── task.py +├── migrations/ +│ ├── env.py +│ ├── README +│ ├── script.py.mako +│ └── versions/ +│ └── 6e1b8a0e43c1_create_task_table.py +├── main.py +└── requirements.txt +``` + +## Requirements + +- Python 3.8+ +- Dependencies listed in `requirements.txt` + +## Installation + +1. Clone the repository: +```bash +git clone https://github.com/yourusername/taskmanagerapi-daenmk.git +cd taskmanagerapi-daenmk +``` + +2. Create a virtual environment (optional but recommended): +```bash +python -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate +``` + +3. Install dependencies: +```bash +pip install -r requirements.txt +``` + +4. Run database migrations: +```bash +alembic upgrade head +``` + +## Running the Application + +Start the FastAPI server: + +```bash +uvicorn main:app --reload +``` + +The API will be available at http://localhost:8000 + +## API Documentation + +FastAPI generates interactive API documentation: + +- Swagger UI: http://localhost:8000/docs +- ReDoc: http://localhost:8000/redoc + +## API Endpoints + +### Health Check + +- `GET /health` - Check if the API is running + +### Tasks + +- `GET /api/v1/tasks` - List all tasks (with optional filtering and pagination) +- `POST /api/v1/tasks` - Create a new task +- `GET /api/v1/tasks/{task_id}` - Get a specific task +- `PUT /api/v1/tasks/{task_id}` - Update a task +- `DELETE /api/v1/tasks/{task_id}` - Delete a task + +## Task Schema + +```json +{ + "title": "string", + "description": "string", + "status": "string", + "priority": "string", + "due_date": "datetime", + "completed": false +} +``` + +## Query Parameters + +For the `GET /api/v1/tasks` endpoint: + +- `skip` (int, default=0): Number of records to skip for pagination +- `limit` (int, default=100): Maximum number of records to return +- `status` (string, optional): Filter tasks by status (e.g., "pending", "completed") + +## Development + +### Linting + +Lint your code using Ruff: + +```bash +ruff check . +``` + +Fix linting issues automatically: + +```bash +ruff check --fix . +``` + +### Database Migrations + +Create a new migration after model changes: + +```bash +alembic revision --autogenerate -m "description of changes" +``` + +Apply migrations: + +```bash +alembic upgrade head +``` + +## License + +MIT \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..c815749 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,41 @@ +[alembic] +script_location = migrations +prepend_sys_path = . +version_path_separator = os + +# SQLite URL - using absolute path +sqlalchemy.url = sqlite:////app/storage/db/db.sqlite + +[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/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..51140ab --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +"""Task Manager API application.""" \ No newline at end of file diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..b8bef7f --- /dev/null +++ b/app/api/__init__.py @@ -0,0 +1 @@ +"""API module for Task Manager.""" \ No newline at end of file diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py new file mode 100644 index 0000000..ce50d26 --- /dev/null +++ b/app/api/v1/__init__.py @@ -0,0 +1 @@ +"""API v1 endpoints.""" \ No newline at end of file diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000..95a59fc --- /dev/null +++ b/app/api/v1/endpoints/__init__.py @@ -0,0 +1 @@ +"""API endpoint modules.""" \ No newline at end of file diff --git a/app/api/v1/endpoints/tasks.py b/app/api/v1/endpoints/tasks.py new file mode 100644 index 0000000..5f55280 --- /dev/null +++ b/app/api/v1/endpoints/tasks.py @@ -0,0 +1,132 @@ +from typing import List, Optional +from fastapi import APIRouter, Depends, HTTPException, Query, status +from sqlalchemy.orm import Session + +from app.database.deps import get_db +from app.models.task import Task +from app.schemas.task import TaskCreate, TaskResponse, TaskUpdate + +router = APIRouter() + + +@router.post( + "/", + response_model=TaskResponse, + status_code=status.HTTP_201_CREATED +) +def create_task( + task_in: TaskCreate, + db: Session = Depends(get_db) +): + """Create a new task.""" + db_task = Task( + title=task_in.title, + description=task_in.description, + status=task_in.status, + priority=task_in.priority, + due_date=task_in.due_date, + completed=task_in.completed + ) + db.add(db_task) + db.commit() + db.refresh(db_task) + return db_task + + +@router.get( + "/", + response_model=List[TaskResponse] +) +def list_tasks( + skip: int = 0, + limit: int = 100, + status: Optional[str] = Query(None, description="Filter tasks by status"), + db: Session = Depends(get_db) +): + """List all tasks with optional filtering.""" + query = db.query(Task) + + # Apply filters if provided + if status: + query = query.filter(Task.status == status) + + # Apply pagination + tasks = query.offset(skip).limit(limit).all() + return tasks + + +@router.get( + "/{task_id}", + response_model=TaskResponse +) +def get_task( + task_id: int, + db: Session = Depends(get_db) +): + """Get a specific task by ID.""" + task = db.query(Task).filter(Task.id == task_id).first() + if task is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Task with ID {task_id} not found" + ) + return task + + +@router.put( + "/{task_id}", + response_model=TaskResponse +) +def update_task( + task_id: int, + task_in: TaskUpdate, + db: Session = Depends(get_db) +): + """Update a task.""" + task = db.query(Task).filter(Task.id == task_id).first() + if task is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Task with ID {task_id} not found" + ) + + # Update task attributes if provided in the request + if task_in.title is not None: + task.title = task_in.title + if task_in.description is not None: + task.description = task_in.description + if task_in.status is not None: + task.status = task_in.status + if task_in.priority is not None: + task.priority = task_in.priority + if task_in.due_date is not None: + task.due_date = task_in.due_date + if task_in.completed is not None: + task.completed = task_in.completed + + db.add(task) + db.commit() + db.refresh(task) + return task + + +@router.delete( + "/{task_id}", + status_code=status.HTTP_204_NO_CONTENT, + response_model=None +) +def delete_task( + task_id: int, + db: Session = Depends(get_db) +): + """Delete a task.""" + task = db.query(Task).filter(Task.id == task_id).first() + if task is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Task with ID {task_id} not found" + ) + + db.delete(task) + db.commit() + return None \ No newline at end of file diff --git a/app/api/v1/router.py b/app/api/v1/router.py new file mode 100644 index 0000000..627dc90 --- /dev/null +++ b/app/api/v1/router.py @@ -0,0 +1,6 @@ +from fastapi import APIRouter + +from app.api.v1.endpoints import tasks + +api_router = APIRouter() +api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"]) \ No newline at end of file diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..0de25ff --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,14 @@ +from pydantic_settings import BaseSettings +from pathlib import Path + + +class Settings(BaseSettings): + PROJECT_NAME: str = "Task Manager API" + API_V1_STR: str = "/api/v1" + + # Database + DB_DIR: Path = Path("/app") / "storage" / "db" + SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite" + + +settings = Settings() \ No newline at end of file diff --git a/app/database/__init__.py b/app/database/__init__.py new file mode 100644 index 0000000..cddd25c --- /dev/null +++ b/app/database/__init__.py @@ -0,0 +1 @@ +"""Database module for Task Manager.""" \ No newline at end of file diff --git a/app/database/base.py b/app/database/base.py new file mode 100644 index 0000000..609c9d8 --- /dev/null +++ b/app/database/base.py @@ -0,0 +1 @@ +# Import all the models to ensure they are registered with SQLAlchemy diff --git a/app/database/base_class.py b/app/database/base_class.py new file mode 100644 index 0000000..df4bcda --- /dev/null +++ b/app/database/base_class.py @@ -0,0 +1,13 @@ +from typing import Any +from sqlalchemy.ext.declarative import as_declarative, declared_attr + + +@as_declarative() +class Base: + id: Any + __name__: str + + # Generate __tablename__ automatically + @declared_attr + def __tablename__(cls) -> str: + return cls.__name__.lower() \ No newline at end of file diff --git a/app/database/deps.py b/app/database/deps.py new file mode 100644 index 0000000..8b0becf --- /dev/null +++ b/app/database/deps.py @@ -0,0 +1,15 @@ +from typing import Generator +from sqlalchemy.orm import Session + +from app.database.session import SessionLocal + + +def get_db() -> Generator[Session, None, None]: + """ + Dependency function that yields a SQLAlchemy session + """ + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/database/session.py b/app/database/session.py new file mode 100644 index 0000000..75490a0 --- /dev/null +++ b/app/database/session.py @@ -0,0 +1,14 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +# Ensure the database directory exists +settings.DB_DIR.mkdir(parents=True, exist_ok=True) + +engine = create_engine( + settings.SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} # Needed for SQLite +) + +SessionLocal = sessionmaker(autocommit=False, autoflush=False, 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..339c662 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +"""Database models for Task Manager.""" \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py new file mode 100644 index 0000000..efc978c --- /dev/null +++ b/app/models/task.py @@ -0,0 +1,18 @@ +from datetime import datetime +from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean + +from app.database.base_class import Base + + +class Task(Base): + """Task database model.""" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String(255), index=True, nullable=False) + description = Column(Text, nullable=True) + status = Column(String(50), default="pending", index=True) + priority = Column(String(50), default="medium") + due_date = Column(DateTime, nullable=True) + completed = Column(Boolean, default=False) + created_at = Column(DateTime, default=datetime.utcnow) + updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..865ca04 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1 @@ +"""Pydantic schemas for Task Manager.""" \ No newline at end of file diff --git a/app/schemas/task.py b/app/schemas/task.py new file mode 100644 index 0000000..5e98b1c --- /dev/null +++ b/app/schemas/task.py @@ -0,0 +1,38 @@ +from datetime import datetime +from typing import Optional +from pydantic import BaseModel + + +class TaskBase(BaseModel): + """Base Task schema with shared attributes.""" + title: str + description: Optional[str] = None + status: Optional[str] = "pending" + priority: Optional[str] = "medium" + due_date: Optional[datetime] = None + completed: Optional[bool] = False + + +class TaskCreate(TaskBase): + """Schema for creating a new task.""" + pass + + +class TaskUpdate(BaseModel): + """Schema for updating an existing task.""" + title: Optional[str] = None + description: Optional[str] = None + status: Optional[str] = None + priority: Optional[str] = None + due_date: Optional[datetime] = None + completed: Optional[bool] = None + + +class TaskResponse(TaskBase): + """Schema for task responses with database fields.""" + id: int + created_at: datetime + updated_at: datetime + + 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..01d3b49 --- /dev/null +++ b/main.py @@ -0,0 +1,31 @@ +import uvicorn +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.api.v1.router import api_router +from app.core.config import settings + +app = FastAPI( + title=settings.PROJECT_NAME, + openapi_url="/openapi.json", +) + +# Set all CORS enabled origins +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(api_router) + + +@app.get("/health", tags=["health"]) +async def health(): + return {"status": "ok"} + + +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/migrations/README b/migrations/README new file mode 100644 index 0000000..e8952c0 --- /dev/null +++ b/migrations/README @@ -0,0 +1,3 @@ +Generic single-database configuration for Task Manager API. + +This directory contains Alembic migrations for the Task Manager API database. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..1b84831 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,65 @@ +import sys +from logging.config import fileConfig +from pathlib import Path + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) + +# add app directory to Python path +sys.path.append(str(Path(__file__).parent.parent)) + +# import models (must be after adding app directory to Python path) +from app.database.base import Base # noqa: E402 + +# target metadata +target_metadata = Base.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode.""" + 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(): + """Run migrations in 'online' mode.""" + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + is_sqlite = connection.dialect.name == 'sqlite' + context.configure( + connection=connection, + target_metadata=target_metadata, + render_as_batch=is_sqlite # Use batch mode for SQLite + ) + + 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/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..1e4564e --- /dev/null +++ b/migrations/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(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/migrations/versions/6e1b8a0e43c1_create_task_table.py b/migrations/versions/6e1b8a0e43c1_create_task_table.py new file mode 100644 index 0000000..c35730e --- /dev/null +++ b/migrations/versions/6e1b8a0e43c1_create_task_table.py @@ -0,0 +1,48 @@ +"""create task table + +Revision ID: 6e1b8a0e43c1 +Revises: +Create Date: 2023-09-20 10:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '6e1b8a0e43c1' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # Create the task table + op.create_table( + 'task', + 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.String(length=50), nullable=True), + sa.Column('priority', sa.String(length=50), nullable=True), + sa.Column('due_date', sa.DateTime(), nullable=True), + sa.Column('completed', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + + # Create indexes + op.create_index(op.f('ix_task_id'), 'task', ['id'], unique=False) + op.create_index(op.f('ix_task_title'), 'task', ['title'], unique=False) + op.create_index(op.f('ix_task_status'), 'task', ['status'], unique=False) + + +def downgrade(): + # Drop indexes + op.drop_index(op.f('ix_task_status'), table_name='task') + op.drop_index(op.f('ix_task_title'), table_name='task') + op.drop_index(op.f('ix_task_id'), table_name='task') + + # Drop the task table + op.drop_table('task') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..d5d4a0b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +fastapi>=0.103.1 +uvicorn>=0.23.2 +sqlalchemy>=2.0.20 +alembic>=1.12.0 +pydantic>=2.3.0 +pydantic-settings>=2.0.3 +python-dotenv>=1.0.0 +ruff>=0.0.290 \ No newline at end of file