Implement Task Manager API with FastAPI and SQLite

Create a full-featured task management API with the following components:
- RESTful CRUD operations for tasks
- Task status and priority management
- SQLite database with SQLAlchemy ORM
- Alembic migrations
- Health check endpoint
- Comprehensive API documentation
This commit is contained in:
Automated Action 2025-05-30 22:50:55 +00:00
parent 00153c7aca
commit ba478ce2d3
23 changed files with 965 additions and 2 deletions

114
README.md
View File

@ -1,3 +1,113 @@
# 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
- Create, read, update, and delete tasks
- Filter tasks by status and title
- Task prioritization
- Due date management
- Health check endpoint for monitoring
- Comprehensive API documentation
## Tech Stack
- **FastAPI**: Modern, fast web framework for building APIs
- **SQLAlchemy**: SQL toolkit and Object-Relational Mapping
- **Alembic**: Database migration tool
- **SQLite**: Lightweight, file-based database
- **Pydantic**: Data validation and settings management
- **Uvicorn**: ASGI server
## Project Structure
```
taskmanagerapi/
├── alembic.ini # Alembic configuration
├── main.py # Application entry point
├── README.md # Project documentation
├── requirements.txt # Project dependencies
├── app/ # Application package
│ ├── api/ # API endpoints
│ │ └── api_v1/ # API version 1
│ │ ├── api.py # API router
│ │ └── endpoints/# API endpoint modules
│ ├── core/ # Core application code
│ │ └── config.py # Configuration settings
│ ├── crud/ # CRUD operations
│ ├── db/ # Database setup
│ ├── models/ # SQLAlchemy models
│ └── schemas/ # Pydantic schemas
└── migrations/ # Database migrations
├── env.py # Alembic environment
├── script.py.mako # Migration script template
└── versions/ # Migration versions
```
## Getting Started
### Prerequisites
- Python 3.8+
### Installation
1. Clone the repository:
```bash
git clone https://github.com/yourusername/taskmanagerapi.git
cd taskmanagerapi
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Run the application:
```bash
uvicorn main:app --reload
```
4. Access the API at `http://localhost:8000`
5. Access the API documentation at `http://localhost:8000/docs` or `http://localhost:8000/redoc`
## API Endpoints
### Health Check
- `GET /api/v1/health`: Check the health of the application
### Tasks
- `GET /api/v1/tasks`: List all tasks
- `POST /api/v1/tasks`: Create a new task
- `GET /api/v1/tasks/{id}`: Get a specific task
- `PUT /api/v1/tasks/{id}`: Update a specific task
- `DELETE /api/v1/tasks/{id}`: Delete a specific task
## Task Model
```json
{
"id": 1,
"title": "Complete project",
"description": "Finish the project by the deadline",
"status": "todo",
"priority": "high",
"due_date": "2023-12-31T23:59:59",
"created_at": "2023-09-01T12:00:00",
"updated_at": "2023-09-01T12:00:00"
}
```
## Filtering Tasks
- By status: `GET /api/v1/tasks?status=todo`
- By title: `GET /api/v1/tasks?title=project`
- Pagination: `GET /api/v1/tasks?skip=0&limit=10`
## License
This project is licensed under the MIT License.

84
alembic.ini Normal file
View File

@ -0,0 +1,84 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; this defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat migrations/versions
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks=black
# black.type=console_scripts
# black.entrypoint=black
# black.options=-l 79
# Logging configuration
[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

View File

@ -0,0 +1,3 @@
"""
API v1 package.
"""

10
app/api/api_v1/api.py Normal file
View File

@ -0,0 +1,10 @@
"""
API router for all endpoints.
"""
from fastapi import APIRouter
from app.api.api_v1.endpoints import health, tasks
api_router = APIRouter()
api_router.include_router(health.router, prefix="/health", tags=["health"])
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])

View File

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

View File

@ -0,0 +1,39 @@
"""
Health check endpoint.
"""
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.db.session import get_db
router = APIRouter()
class HealthCheck(BaseModel):
"""
Health check response schema.
"""
status: str
database: bool
@router.get("", response_model=HealthCheck)
def health_check(db: Session = Depends(get_db)):
"""
Health check endpoint.
Returns:
HealthCheck: Health status including database connectivity.
"""
# Check if database is accessible
try:
db.execute("SELECT 1")
db_status = True
except Exception:
db_status = False
return {
"status": "healthy",
"database": db_status
}

View File

@ -0,0 +1,147 @@
"""
Task API endpoints.
"""
from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.crud import crud_task
from app.db.session import get_db
from app.models.task import TaskStatus
from app.schemas.task import Task, TaskCreate, TaskUpdate
router = APIRouter()
@router.get("", response_model=List[Task])
def read_tasks(
db: Session = Depends(get_db),
status: Optional[TaskStatus] = None,
title: Optional[str] = None,
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve tasks.
Args:
db: Database session.
status: Filter by task status.
title: Filter by task title (partial match).
skip: Number of records to skip.
limit: Maximum number of records to return.
Returns:
List[Task]: List of tasks.
"""
if status:
return crud_task.task.get_by_status(db, status=status, skip=skip, limit=limit)
elif title:
return crud_task.task.get_by_title(db, title=title, skip=skip, limit=limit)
return crud_task.task.get_multi(db, skip=skip, limit=limit)
@router.post("", response_model=Task, status_code=status.HTTP_201_CREATED)
def create_task(
*,
db: Session = Depends(get_db),
task_in: TaskCreate,
) -> Any:
"""
Create new task.
Args:
db: Database session.
task_in: Task data.
Returns:
Task: Created task.
"""
task = crud_task.task.create(db=db, obj_in=task_in)
return task
@router.get("/{id}", response_model=Task)
def read_task(
*,
db: Session = Depends(get_db),
id: int,
) -> Any:
"""
Get task by ID.
Args:
db: Database session.
id: Task ID.
Returns:
Task: Task with specified ID.
Raises:
HTTPException: If task not found.
"""
task = crud_task.task.get(db=db, id=id)
if not task:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Task not found",
)
return task
@router.put("/{id}", response_model=Task)
def update_task(
*,
db: Session = Depends(get_db),
id: int,
task_in: TaskUpdate,
) -> Any:
"""
Update a task.
Args:
db: Database session.
id: Task ID.
task_in: Task update data.
Returns:
Task: Updated task.
Raises:
HTTPException: If task not found.
"""
task = crud_task.task.get(db=db, id=id)
if not task:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Task not found",
)
task = crud_task.task.update(db=db, db_obj=task, obj_in=task_in)
return task
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_task(
*,
db: Session = Depends(get_db),
id: int,
) -> None:
"""
Delete a task.
Args:
db: Database session.
id: Task ID.
Raises:
HTTPException: If task not found.
"""
task = crud_task.task.get(db=db, id=id)
if not task:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Task not found",
)
crud_task.task.remove(db=db, id=id)
return None

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

@ -0,0 +1,35 @@
"""
Configuration settings for the Task Manager API.
"""
from typing import List, Union
from pydantic import AnyHttpUrl, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""
Application settings. Loads from environment variables.
"""
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", case_sensitive=True)
API_V1_STR: str = "/api/v1"
API_VERSION: str = "0.1.0"
PROJECT_NAME: str = "Task Manager API"
# CORS settings
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
@field_validator("BACKEND_CORS_ORIGINS", mode="before")
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
"""
Parse CORS origins from environment variable.
"""
if isinstance(v, str) and not v.startswith("["):
return [i.strip() for i in v.split(",")]
elif isinstance(v, (list, str)):
return v
raise ValueError(v)
settings = Settings()

3
app/crud/__init__.py Normal file
View File

@ -0,0 +1,3 @@
"""
CRUD operations.
"""

82
app/crud/base.py Normal file
View File

@ -0,0 +1,82 @@
"""
Base CRUD operations.
"""
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.db.base_class import Base
ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
"""
Base class for CRUD operations.
"""
def __init__(self, model: Type[ModelType]):
"""
Initialize with SQLAlchemy model.
"""
self.model = model
def get(self, db: Session, id: Any) -> Optional[ModelType]:
"""
Get an object by ID.
"""
return db.query(self.model).filter(self.model.id == id).first()
def get_multi(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[ModelType]:
"""
Get multiple objects.
"""
return db.query(self.model).offset(skip).limit(limit).all()
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
"""
Create a new object.
"""
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data) # type: ignore
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
self,
db: Session,
*,
db_obj: ModelType,
obj_in: Union[UpdateSchemaType, Dict[str, Any]]
) -> ModelType:
"""
Update an object.
"""
obj_data = jsonable_encoder(db_obj)
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.model_dump(exclude_unset=True)
for field in obj_data:
if field in update_data:
setattr(db_obj, field, update_data[field])
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def remove(self, db: Session, *, id: int) -> ModelType:
"""
Remove an object.
"""
obj = db.query(self.model).get(id)
db.delete(obj)
db.commit()
return obj

46
app/crud/crud_task.py Normal file
View File

@ -0,0 +1,46 @@
"""
CRUD operations for tasks.
"""
from typing import List
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.task import Task, TaskStatus
from app.schemas.task import TaskCreate, TaskUpdate
class CRUDTask(CRUDBase[Task, TaskCreate, TaskUpdate]):
"""
CRUD operations for tasks.
"""
def get_by_status(
self, db: Session, *, status: TaskStatus, skip: int = 0, limit: int = 100
) -> List[Task]:
"""
Get tasks by status.
"""
return (
db.query(self.model)
.filter(self.model.status == status)
.offset(skip)
.limit(limit)
.all()
)
def get_by_title(
self, db: Session, *, title: str, skip: int = 0, limit: int = 100
) -> List[Task]:
"""
Get tasks by title (partial match).
"""
return (
db.query(self.model)
.filter(self.model.title.ilike(f"%{title}%"))
.offset(skip)
.limit(limit)
.all()
)
task = CRUDTask(Task)

7
app/db/base.py Normal file
View File

@ -0,0 +1,7 @@
"""
Import all the models, so that Base has them before being
imported by Alembic
"""
from app.db.base_class import Base # noqa
from app.models.task import Task # noqa

20
app/db/base_class.py Normal file
View File

@ -0,0 +1,20 @@
"""
SQLAlchemy base class for all models.
"""
from typing import Any
from sqlalchemy.ext.declarative import as_declarative, declared_attr
@as_declarative()
class Base:
"""
Base class for all models.
"""
id: Any
__name__: str
# Generate __tablename__ automatically
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()

14
app/db/init_db.py Normal file
View File

@ -0,0 +1,14 @@
"""
Database initialization.
"""
from sqlalchemy.orm import Session
from app.db import base # noqa: F401
def init_db(db: Session) -> None:
"""
Initialize the database.
"""
# Any initialization logic can be added here
pass

29
app/db/session.py Normal file
View File

@ -0,0 +1,29 @@
"""
Database session configuration.
"""
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():
"""
Get a database session.
"""
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1,46 @@
"""
Task model definition.
"""
from datetime import datetime
from enum import Enum
from sqlalchemy import Column, DateTime, Enum as SQLAlchemyEnum, Integer, String, Text
from app.db.base_class import Base
class TaskStatus(str, Enum):
"""
Task status enumeration.
"""
TODO = "todo"
IN_PROGRESS = "in_progress"
DONE = "done"
class TaskPriority(str, Enum):
"""
Task priority enumeration.
"""
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
class Task(Base):
"""
Task model.
"""
id = Column(Integer, primary_key=True, index=True)
title = Column(String(255), nullable=False, index=True)
description = Column(Text, nullable=True)
status = Column(SQLAlchemyEnum(TaskStatus), default=TaskStatus.TODO, nullable=False)
priority = Column(SQLAlchemyEnum(TaskPriority), default=TaskPriority.MEDIUM, nullable=False)
due_date = Column(DateTime, nullable=True)
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
updated_at = Column(
DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False
)

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

@ -0,0 +1,3 @@
"""
Pydantic schemas for the API.
"""

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

@ -0,0 +1,73 @@
"""
Task schemas for validation and serialization.
"""
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
from app.models.task import TaskPriority, TaskStatus
# Shared properties
class TaskBase(BaseModel):
"""
Base properties shared by all task schemas.
"""
title: str = Field(..., min_length=1, max_length=255, description="Task title")
description: Optional[str] = Field(None, description="Task description")
status: TaskStatus = Field(default=TaskStatus.TODO, description="Task status")
priority: TaskPriority = Field(default=TaskPriority.MEDIUM, description="Task priority")
due_date: Optional[datetime] = Field(None, description="Task due date")
# Properties to receive on task creation
class TaskCreate(TaskBase):
"""
Properties to receive on task creation.
"""
pass
# Properties to receive on task update
class TaskUpdate(BaseModel):
"""
Properties to receive on task update.
"""
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")
# Properties shared by models stored in DB
class TaskInDBBase(TaskBase):
"""
Properties shared by models stored in DB.
"""
id: int
created_at: datetime
updated_at: datetime
class Config:
"""
Pydantic configuration.
"""
from_attributes = True
# Properties to return to client
class Task(TaskInDBBase):
"""
Properties to return to client.
"""
pass
# Properties stored in DB
class TaskInDB(TaskInDBBase):
"""
Properties stored in DB.
"""
pass

51
main.py Normal file
View File

@ -0,0 +1,51 @@
"""
Task Manager API
A FastAPI-based REST API for managing tasks.
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.utils import get_openapi
from app.api.api_v1.api import api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url="/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router, prefix=settings.API_V1_STR)
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title=settings.PROJECT_NAME,
version=settings.API_VERSION,
description="API for managing tasks",
routes=app.routes,
)
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

82
migrations/env.py Normal file
View File

@ -0,0 +1,82 @@
"""
Alembic environment configuration.
"""
from logging.config import fileConfig
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 your model's MetaData object here
# for 'autogenerate' support
from app.db.base import Base # noqa
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
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.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
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 # Key configuration 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,40 @@
"""Create tasks table
Revision ID: 0001
Revises:
Create Date: 2023-09-01 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# Create task status enum
op.create_table(
'task',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(255), nullable=False, index=True),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('status', sa.Enum('todo', 'in_progress', 'done', 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_task_id'), 'task', ['id'], unique=False)
def downgrade():
op.drop_index(op.f('ix_task_id'), table_name='task')
op.drop_table('task')
op.execute('DROP TYPE taskstatus')
op.execute('DROP TYPE taskpriority')

12
requirements.txt Normal file
View File

@ -0,0 +1,12 @@
fastapi>=0.100.0,<0.101.0
uvicorn>=0.22.0,<0.23.0
sqlalchemy>=2.0.0,<2.1.0
alembic>=1.11.0,<1.12.0
pydantic>=2.0.0,<2.1.0
pydantic-settings>=2.0.0,<2.1.0
python-dotenv>=1.0.0,<1.1.0
python-multipart>=0.0.6,<0.0.7
email-validator>=2.0.0,<2.1.0
ruff>=0.0.0
httpx>=0.24.0,<0.25.0
pytest>=7.3.1,<7.4.0