Build complete task management tool with FastAPI and SQLite
- Implemented CRUD operations for task management - Added task status tracking (pending, in_progress, completed) - Included priority levels (low, medium, high) - Set up SQLite database with Alembic migrations - Added filtering and pagination support - Configured CORS for all origins - Included health check endpoint - Added comprehensive API documentation - Formatted code with Ruff linting
This commit is contained in:
parent
c3d600af5f
commit
97c3923628
88
README.md
88
README.md
@ -1,3 +1,87 @@
|
||||
# FastAPI Application
|
||||
# Task Management Tool
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
A simple and efficient task management API built with FastAPI and SQLite.
|
||||
|
||||
## Features
|
||||
|
||||
- **CRUD Operations**: Create, read, update, and delete tasks
|
||||
- **Task Status Management**: Track tasks as pending, in progress, or completed
|
||||
- **Priority Levels**: Set task priorities (low, medium, high)
|
||||
- **Filtering**: Filter tasks by status and priority
|
||||
- **Pagination**: Support for skip/limit pagination
|
||||
- **Health Check**: Built-in health monitoring endpoint
|
||||
- **Interactive Documentation**: Automatic API documentation with Swagger UI
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Base
|
||||
- `GET /` - Service information and documentation links
|
||||
- `GET /health` - Health check endpoint
|
||||
|
||||
### Tasks
|
||||
- `POST /api/v1/tasks/` - Create a new task
|
||||
- `GET /api/v1/tasks/` - List all tasks (with filtering and pagination)
|
||||
- `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
|
||||
|
||||
### Query Parameters for GET /api/v1/tasks/
|
||||
- `skip`: Number of tasks to skip (default: 0)
|
||||
- `limit`: Number of tasks to return (default: 100, max: 1000)
|
||||
- `status`: Filter by task status (pending, in_progress, completed)
|
||||
- `priority`: Filter by task priority (low, medium, high)
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
The application will be available at:
|
||||
- API: http://localhost:8000
|
||||
- Documentation: http://localhost:8000/docs
|
||||
- Alternative Documentation: http://localhost:8000/redoc
|
||||
- OpenAPI Schema: http://localhost:8000/openapi.json
|
||||
|
||||
## Database
|
||||
|
||||
This application uses SQLite as the database backend. The database file is stored at `/app/storage/db/db.sqlite`.
|
||||
|
||||
Database migrations are handled with Alembic. The initial migration creates the tasks table with the following schema:
|
||||
|
||||
- `id`: Primary key (integer)
|
||||
- `title`: Task title (string, max 200 characters)
|
||||
- `description`: Optional task description (text)
|
||||
- `status`: Task status enum (pending, in_progress, completed)
|
||||
- `priority`: Task priority enum (low, medium, high)
|
||||
- `created_at`: Creation timestamp
|
||||
- `updated_at`: Last update timestamp
|
||||
|
||||
## Development
|
||||
|
||||
The codebase follows these conventions:
|
||||
- Code formatting with Ruff
|
||||
- SQLAlchemy for database ORM
|
||||
- Pydantic for data validation
|
||||
- FastAPI for the web framework
|
||||
- CORS enabled for all origins
|
||||
|
||||
## Task Model
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Sample Task",
|
||||
"description": "This is a sample task description",
|
||||
"status": "pending",
|
||||
"priority": "medium",
|
||||
"created_at": "2024-01-01T12:00:00Z",
|
||||
"updated_at": "2024-01-01T12:00:00Z"
|
||||
}
|
||||
```
|
||||
|
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
|
59
alembic/env.py
Normal file
59
alembic/env.py
Normal file
@ -0,0 +1,59 @@
|
||||
from logging.config import fileConfig
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
from alembic import context
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the project root to the Python path
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from app.db.base import Base
|
||||
|
||||
# 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.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""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() -> None:
|
||||
"""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:
|
||||
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"}
|
56
alembic/versions/001_create_tasks_table.py
Normal file
56
alembic/versions/001_create_tasks_table.py
Normal file
@ -0,0 +1,56 @@
|
||||
"""Create tasks table
|
||||
|
||||
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:
|
||||
op.create_table(
|
||||
"tasks",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("title", sa.String(length=200), 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(timezone=True),
|
||||
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||
nullable=True,
|
||||
),
|
||||
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")
|
72
app/api/tasks.py
Normal file
72
app/api/tasks.py
Normal file
@ -0,0 +1,72 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
from app.db.session import get_db
|
||||
from app.models.task import Task, TaskStatus, TaskPriority
|
||||
from app.schemas.task import TaskCreate, TaskUpdate, TaskResponse
|
||||
|
||||
router = APIRouter(prefix="/tasks", tags=["tasks"])
|
||||
|
||||
|
||||
@router.post("/", response_model=TaskResponse, status_code=201)
|
||||
def create_task(task: TaskCreate, db: Session = Depends(get_db)):
|
||||
db_task = Task(**task.dict())
|
||||
db.add(db_task)
|
||||
db.commit()
|
||||
db.refresh(db_task)
|
||||
return db_task
|
||||
|
||||
|
||||
@router.get("/", response_model=List[TaskResponse])
|
||||
def get_tasks(
|
||||
skip: int = Query(0, ge=0, description="Number of tasks to skip"),
|
||||
limit: int = Query(100, ge=1, le=1000, description="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"
|
||||
),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
query = db.query(Task)
|
||||
|
||||
if status:
|
||||
query = query.filter(Task.status == status)
|
||||
if priority:
|
||||
query = query.filter(Task.priority == priority)
|
||||
|
||||
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)):
|
||||
task = db.query(Task).filter(Task.id == task_id).first()
|
||||
if not task:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return task
|
||||
|
||||
|
||||
@router.put("/{task_id}", response_model=TaskResponse)
|
||||
def update_task(task_id: int, task_update: TaskUpdate, db: Session = Depends(get_db)):
|
||||
task = db.query(Task).filter(Task.id == task_id).first()
|
||||
if not task:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
|
||||
update_data = task_update.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(task, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(task)
|
||||
return task
|
||||
|
||||
|
||||
@router.delete("/{task_id}", status_code=204)
|
||||
def delete_task(task_id: int, db: Session = Depends(get_db)):
|
||||
task = db.query(Task).filter(Task.id == task_id).first()
|
||||
if not task:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
|
||||
db.delete(task)
|
||||
db.commit()
|
||||
return None
|
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()
|
30
app/models/task.py
Normal file
30
app/models/task.py
Normal file
@ -0,0 +1,30 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, Enum
|
||||
from sqlalchemy.sql import func
|
||||
from enum import Enum as PyEnum
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class TaskStatus(PyEnum):
|
||||
PENDING = "pending"
|
||||
IN_PROGRESS = "in_progress"
|
||||
COMPLETED = "completed"
|
||||
|
||||
|
||||
class TaskPriority(PyEnum):
|
||||
LOW = "low"
|
||||
MEDIUM = "medium"
|
||||
HIGH = "high"
|
||||
|
||||
|
||||
class Task(Base):
|
||||
__tablename__ = "tasks"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
title = Column(String(200), 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(timezone=True), server_default=func.now())
|
||||
updated_at = Column(
|
||||
DateTime(timezone=True), onupdate=func.now(), server_default=func.now()
|
||||
)
|
33
app/schemas/task.py
Normal file
33
app/schemas/task.py
Normal file
@ -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(..., max_length=200, description="Task title")
|
||||
description: Optional[str] = Field(None, description="Task description")
|
||||
status: TaskStatus = Field(default=TaskStatus.PENDING, description="Task status")
|
||||
priority: TaskPriority = Field(
|
||||
default=TaskPriority.MEDIUM, description="Task priority"
|
||||
)
|
||||
|
||||
|
||||
class TaskCreate(TaskBase):
|
||||
pass
|
||||
|
||||
|
||||
class TaskUpdate(BaseModel):
|
||||
title: Optional[str] = Field(None, max_length=200, 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")
|
||||
|
||||
|
||||
class TaskResponse(TaskBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
47
main.py
Normal file
47
main.py
Normal file
@ -0,0 +1,47 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.db.session import engine
|
||||
from app.db.base import Base
|
||||
from app.api.tasks import router as tasks_router
|
||||
|
||||
# Create database tables
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI(
|
||||
title="Task Management Tool",
|
||||
description="A simple task management API",
|
||||
version="1.0.0",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
# CORS configuration
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Include routers
|
||||
app.include_router(tasks_router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {
|
||||
"title": "Task Management Tool",
|
||||
"documentation": "/docs",
|
||||
"health": "/health",
|
||||
}
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "healthy", "service": "task-management-tool"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(app, host="0.0.0.0", port=8000)
|
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.13.1
|
||||
pydantic==2.5.2
|
||||
python-multipart==0.0.6
|
||||
ruff==0.1.8
|
Loading…
x
Reference in New Issue
Block a user