Implement Task Manager API with FastAPI and SQLite

- Set up project structure
- Configure SQLAlchemy models and database connection
- Set up Alembic for database migrations
- Create Pydantic schemas for API data validation
- Implement task CRUD operations
- Add task filtering and pagination
- Include health check endpoint
- Update README with setup and usage instructions
This commit is contained in:
Automated Action 2025-06-04 20:37:13 +00:00
parent 8971f55a9d
commit 3be833dc43
24 changed files with 635 additions and 2 deletions

159
README.md
View File

@ -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

41
alembic.ini Normal file
View File

@ -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

1
app/__init__.py Normal file
View File

@ -0,0 +1 @@
"""Task Manager API application."""

1
app/api/__init__.py Normal file
View File

@ -0,0 +1 @@
"""API module for Task Manager."""

1
app/api/v1/__init__.py Normal file
View File

@ -0,0 +1 @@
"""API v1 endpoints."""

View File

@ -0,0 +1 @@
"""API endpoint modules."""

View File

@ -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

6
app/api/v1/router.py Normal file
View File

@ -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"])

14
app/core/config.py Normal file
View File

@ -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()

1
app/database/__init__.py Normal file
View File

@ -0,0 +1 @@
"""Database module for Task Manager."""

1
app/database/base.py Normal file
View File

@ -0,0 +1 @@
# Import all the models to ensure they are registered with SQLAlchemy

View File

@ -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()

15
app/database/deps.py Normal file
View File

@ -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()

14
app/database/session.py Normal file
View File

@ -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)

1
app/models/__init__.py Normal file
View File

@ -0,0 +1 @@
"""Database models for Task Manager."""

18
app/models/task.py Normal file
View File

@ -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)

1
app/schemas/__init__.py Normal file
View File

@ -0,0 +1 @@
"""Pydantic schemas for Task Manager."""

38
app/schemas/task.py Normal file
View File

@ -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

31
main.py Normal file
View File

@ -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)

3
migrations/README Normal file
View File

@ -0,0 +1,3 @@
Generic single-database configuration for Task Manager API.
This directory contains Alembic migrations for the Task Manager API database.

65
migrations/env.py Normal file
View File

@ -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()

24
migrations/script.py.mako Normal file
View 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():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@ -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')

8
requirements.txt Normal file
View File

@ -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