Implement comprehensive Task Manager API with FastAPI
Added complete task management functionality including: - CRUD operations for tasks (create, read, update, delete) - Task model with status (pending/in_progress/completed) and priority (low/medium/high) - SQLite database with SQLAlchemy ORM - Alembic migrations for database schema - Pydantic schemas for request/response validation - FastAPI routers with proper error handling - Filtering and pagination support - Health check endpoint - CORS configuration - Comprehensive API documentation - Proper project structure following FastAPI best practices
This commit is contained in:
parent
03b925afb5
commit
10172c55ca
113
README.md
113
README.md
@ -1,3 +1,112 @@
|
||||
# FastAPI Application
|
||||
# Task Manager API
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
A comprehensive task management API built with FastAPI, SQLAlchemy, and SQLite. This API provides full CRUD operations for managing tasks with status tracking, priority levels, and timestamps.
|
||||
|
||||
## Features
|
||||
|
||||
- ✅ Create, read, update, and delete tasks
|
||||
- ✅ Task status management (pending, in_progress, completed)
|
||||
- ✅ Priority levels (low, medium, high)
|
||||
- ✅ Automatic timestamps (created_at, updated_at)
|
||||
- ✅ Filtering by status and priority
|
||||
- ✅ Pagination support
|
||||
- ✅ FastAPI automatic documentation
|
||||
- ✅ SQLite database with SQLAlchemy ORM
|
||||
- ✅ Database migrations with Alembic
|
||||
- ✅ CORS enabled for cross-origin requests
|
||||
- ✅ Health check endpoint
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Base URL
|
||||
- **GET** `/` - API information and links
|
||||
- **GET** `/health` - Health check endpoint
|
||||
|
||||
### Tasks
|
||||
- **POST** `/api/v1/tasks/` - Create a new task
|
||||
- **GET** `/api/v1/tasks/` - Get all tasks (with optional filtering and pagination)
|
||||
- **GET** `/api/v1/tasks/{task_id}` - Get a specific task by ID
|
||||
- **PUT** `/api/v1/tasks/{task_id}` - Update a specific task
|
||||
- **DELETE** `/api/v1/tasks/{task_id}` - Delete a specific task
|
||||
|
||||
### Query Parameters for GET /api/v1/tasks/
|
||||
- `skip` (int): Number of tasks to skip (default: 0)
|
||||
- `limit` (int): Maximum number of tasks to return (default: 100, max: 1000)
|
||||
- `status` (string): Filter by status (`pending`, `in_progress`, `completed`)
|
||||
- `priority` (string): Filter by priority (`low`, `medium`, `high`)
|
||||
|
||||
## Task Schema
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Example Task",
|
||||
"description": "This is an example task description",
|
||||
"status": "pending",
|
||||
"priority": "medium",
|
||||
"created_at": "2025-06-20T12:00:00",
|
||||
"updated_at": "2025-06-20T12:00:00"
|
||||
}
|
||||
```
|
||||
|
||||
### Status Values
|
||||
- `pending` - Task is not yet started
|
||||
- `in_progress` - Task is currently being worked on
|
||||
- `completed` - Task has been finished
|
||||
|
||||
### Priority Values
|
||||
- `low` - Low priority task
|
||||
- `medium` - Medium priority task (default)
|
||||
- `high` - High priority task
|
||||
|
||||
## Installation and Setup
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
2. Run database migrations:
|
||||
```bash
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
3. Start the development server:
|
||||
```bash
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
The API will be available at `http://localhost:8000`
|
||||
|
||||
## Documentation
|
||||
|
||||
- **Swagger UI**: http://localhost:8000/docs
|
||||
- **ReDoc**: http://localhost:8000/redoc
|
||||
- **OpenAPI JSON**: http://localhost:8000/openapi.json
|
||||
|
||||
## Environment Variables
|
||||
|
||||
No environment variables are required for basic operation. The application uses SQLite with a local database file stored in `/app/storage/db/db.sqlite`.
|
||||
|
||||
## Development
|
||||
|
||||
The application uses the following structure:
|
||||
- `main.py` - FastAPI application entry point
|
||||
- `app/models/` - SQLAlchemy database models
|
||||
- `app/schemas/` - Pydantic request/response schemas
|
||||
- `app/crud/` - Database operations
|
||||
- `app/routers/` - API route handlers
|
||||
- `app/db/` - Database configuration and session management
|
||||
- `alembic/` - Database migration files
|
||||
|
||||
## Testing
|
||||
|
||||
Run the linter and formatter:
|
||||
```bash
|
||||
ruff check .
|
||||
ruff format .
|
||||
```
|
||||
|
||||
## Production Deployment
|
||||
|
||||
For production deployment, ensure proper database configuration and consider using PostgreSQL instead of SQLite for better performance and concurrent access.
|
||||
|
41
alembic.ini
Normal file
41
alembic.ini
Normal file
@ -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
|
50
alembic/env.py
Normal file
50
alembic/env.py
Normal file
@ -0,0 +1,50 @@
|
||||
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()
|
24
alembic/script.py.mako
Normal file
24
alembic/script.py.mako
Normal file
@ -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"}
|
46
alembic/versions/001_initial_migration.py
Normal file
46
alembic/versions/001_initial_migration.py
Normal file
@ -0,0 +1,46 @@
|
||||
"""Create tasks table
|
||||
|
||||
Revision ID: 001
|
||||
Revises:
|
||||
Create Date: 2025-06-20 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:
|
||||
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("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")
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
3
app/crud/__init__.py
Normal file
3
app/crud/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
from . import task
|
||||
|
||||
__all__ = ["task"]
|
63
app/crud/task.py
Normal file
63
app/crud/task.py
Normal file
@ -0,0 +1,63 @@
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.task import Task
|
||||
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) -> List[Task]:
|
||||
return db.query(Task).offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
def create_task(db: Session, task: TaskCreate) -> Task:
|
||||
db_task = Task(
|
||||
title=task.title,
|
||||
description=task.description,
|
||||
status=task.status,
|
||||
priority=task.priority,
|
||||
)
|
||||
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 db_task is None:
|
||||
return None
|
||||
|
||||
update_data = task_update.model_dump(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 db_task is None:
|
||||
return False
|
||||
|
||||
db.delete(db_task)
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
|
||||
def get_tasks_by_status(
|
||||
db: Session, status: str, skip: int = 0, limit: int = 100
|
||||
) -> List[Task]:
|
||||
return db.query(Task).filter(Task.status == status).offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
def get_tasks_by_priority(
|
||||
db: Session, priority: str, skip: int = 0, limit: int = 100
|
||||
) -> List[Task]:
|
||||
return (
|
||||
db.query(Task).filter(Task.priority == priority).offset(skip).limit(limit).all()
|
||||
)
|
3
app/db/base.py
Normal file
3
app/db/base.py
Normal file
@ -0,0 +1,3 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
Base = declarative_base()
|
22
app/db/session.py
Normal file
22
app/db/session.py
Normal file
@ -0,0 +1,22 @@
|
||||
from pathlib import Path
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
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()
|
3
app/models/__init__.py
Normal file
3
app/models/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
from .task import Task, TaskStatus, TaskPriority
|
||||
|
||||
__all__ = ["Task", "TaskStatus", "TaskPriority"]
|
30
app/models/task.py
Normal file
30
app/models/task.py
Normal file
@ -0,0 +1,30 @@
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, Enum
|
||||
from app.db.base import Base
|
||||
import enum
|
||||
|
||||
|
||||
class TaskStatus(enum.Enum):
|
||||
PENDING = "pending"
|
||||
IN_PROGRESS = "in_progress"
|
||||
COMPLETED = "completed"
|
||||
|
||||
|
||||
class TaskPriority(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)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = Column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
)
|
3
app/routers/__init__.py
Normal file
3
app/routers/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
from .tasks import router as tasks_router
|
||||
|
||||
__all__ = ["tasks_router"]
|
68
app/routers/tasks.py
Normal file
68
app/routers/tasks.py
Normal file
@ -0,0 +1,68 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from app.db.session import get_db
|
||||
from app.crud import task as crud_task
|
||||
from app.schemas.task import Task, TaskCreate, TaskUpdate
|
||||
from app.models.task import TaskStatus, TaskPriority
|
||||
|
||||
router = APIRouter(prefix="/tasks", tags=["tasks"])
|
||||
|
||||
|
||||
@router.post("/", response_model=Task, status_code=201)
|
||||
def create_task(task: TaskCreate, db: Session = Depends(get_db)):
|
||||
return crud_task.create_task(db=db, task=task)
|
||||
|
||||
|
||||
@router.get("/", response_model=List[Task])
|
||||
def get_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: str = Query(None, description="Filter by task status"),
|
||||
priority: str = Query(None, description="Filter by task priority"),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if status:
|
||||
try:
|
||||
status_enum = TaskStatus(status)
|
||||
return crud_task.get_tasks_by_status(
|
||||
db=db, status=status_enum, skip=skip, limit=limit
|
||||
)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid status value")
|
||||
|
||||
if priority:
|
||||
try:
|
||||
priority_enum = TaskPriority(priority)
|
||||
return crud_task.get_tasks_by_priority(
|
||||
db=db, priority=priority_enum, skip=skip, limit=limit
|
||||
)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid priority value")
|
||||
|
||||
return crud_task.get_tasks(db=db, skip=skip, limit=limit)
|
||||
|
||||
|
||||
@router.get("/{task_id}", response_model=Task)
|
||||
def get_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=Task)
|
||||
def update_task(task_id: int, task_update: TaskUpdate, db: Session = Depends(get_db)):
|
||||
db_task = crud_task.update_task(db=db, task_id=task_id, task_update=task_update)
|
||||
if db_task is None:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return db_task
|
||||
|
||||
|
||||
@router.delete("/{task_id}", status_code=204)
|
||||
def delete_task(task_id: int, db: Session = Depends(get_db)):
|
||||
deleted = crud_task.delete_task(db=db, task_id=task_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
3
app/schemas/__init__.py
Normal file
3
app/schemas/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
from .task import Task, TaskCreate, TaskUpdate, TaskBase, TaskInDB
|
||||
|
||||
__all__ = ["Task", "TaskCreate", "TaskUpdate", "TaskBase", "TaskInDB"]
|
35
app/schemas/task.py
Normal file
35
app/schemas/task.py
Normal file
@ -0,0 +1,35 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
from app.models.task import TaskStatus, TaskPriority
|
||||
|
||||
|
||||
class TaskBase(BaseModel):
|
||||
title: str
|
||||
description: Optional[str] = None
|
||||
status: TaskStatus = TaskStatus.PENDING
|
||||
priority: TaskPriority = TaskPriority.MEDIUM
|
||||
|
||||
|
||||
class TaskCreate(TaskBase):
|
||||
pass
|
||||
|
||||
|
||||
class TaskUpdate(BaseModel):
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
status: Optional[TaskStatus] = None
|
||||
priority: Optional[TaskPriority] = None
|
||||
|
||||
|
||||
class TaskInDB(TaskBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class Task(TaskInDB):
|
||||
pass
|
42
main.py
Normal file
42
main.py
Normal file
@ -0,0 +1,42 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.routers.tasks import router as tasks_router
|
||||
from app.db.session import engine
|
||||
from app.db.base import Base
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI(
|
||||
title="Task Manager API",
|
||||
description="A simple task management API built with FastAPI",
|
||||
version="1.0.0",
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(tasks_router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def root():
|
||||
return {
|
||||
"title": "Task Manager API",
|
||||
"description": "A simple task management 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"}
|
7
requirements.txt
Normal file
7
requirements.txt
Normal file
@ -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
|
Loading…
x
Reference in New Issue
Block a user