Add Task Manager API with FastAPI and SQLite
- Created comprehensive task management system with CRUD operations - Implemented SQLAlchemy models and database configuration - Added Alembic migrations for database schema management - Created FastAPI endpoints for task management with proper validation - Added health check endpoint and base URL information - Configured CORS middleware and OpenAPI documentation - Updated README with comprehensive API documentation - Code formatted and linted with Ruff
This commit is contained in:
parent
092c480433
commit
0d6888d900
97
README.md
97
README.md
@ -1,3 +1,96 @@
|
||||
# FastAPI Application
|
||||
# Task Manager API
|
||||
|
||||
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
|
||||
|
||||
- Create, read, update, and delete tasks
|
||||
- Filter tasks by completion status
|
||||
- Filter tasks by priority level
|
||||
- Automatic timestamps for task creation and updates
|
||||
- SQLite database with SQLAlchemy ORM
|
||||
- Database migrations with Alembic
|
||||
- Interactive API documentation with Swagger UI
|
||||
- Health check endpoint
|
||||
- CORS support for cross-origin requests
|
||||
|
||||
## Installation
|
||||
|
||||
1. Clone the repository
|
||||
2. Install dependencies:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Run the application:
|
||||
```bash
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Base Information
|
||||
- `GET /` - API information and available endpoints
|
||||
- `GET /health` - Health check endpoint
|
||||
|
||||
### Task Management
|
||||
- `POST /api/v1/tasks` - Create a new task
|
||||
- `GET /api/v1/tasks` - List all tasks (with optional filtering)
|
||||
- `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
|
||||
- `GET /api/v1/tasks/priority/{priority}` - Get tasks by priority
|
||||
|
||||
### Query Parameters
|
||||
- `skip` - Number of tasks to skip (pagination)
|
||||
- `limit` - Maximum number of tasks to return
|
||||
- `completed` - Filter by completion status (true/false)
|
||||
|
||||
## Task Schema
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Example Task",
|
||||
"description": "Task description",
|
||||
"completed": false,
|
||||
"priority": "medium",
|
||||
"created_at": "2024-01-01T00:00:00",
|
||||
"updated_at": "2024-01-01T00:00:00",
|
||||
"due_date": "2024-01-02T00:00:00"
|
||||
}
|
||||
```
|
||||
|
||||
## Priority Levels
|
||||
- `low`
|
||||
- `medium`
|
||||
- `high`
|
||||
|
||||
## Database
|
||||
|
||||
The application uses SQLite as the database, stored in `/app/storage/db/db.sqlite`. The database schema is managed using Alembic migrations.
|
||||
|
||||
## API Documentation
|
||||
|
||||
Once the application is running, you can access:
|
||||
- Swagger UI: `http://localhost:8000/docs`
|
||||
- ReDoc: `http://localhost:8000/redoc`
|
||||
- OpenAPI JSON: `http://localhost:8000/openapi.json`
|
||||
|
||||
## Development
|
||||
|
||||
### Running with uvicorn
|
||||
```bash
|
||||
uvicorn main:app --reload --host 0.0.0.0 --port 8000
|
||||
```
|
||||
|
||||
### Database Migrations
|
||||
The application automatically creates the database tables on startup. Migration files are located in the `alembic/versions/` directory.
|
||||
|
||||
## Health Check
|
||||
|
||||
The API provides a health check endpoint at `/health` that returns the current status of the service.
|
||||
|
||||
## CORS Configuration
|
||||
|
||||
The API is configured to allow all origins for development purposes. In production, you should restrict this to specific domains.
|
||||
|
42
alembic.ini
Normal file
42
alembic.ini
Normal file
@ -0,0 +1,42 @@
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
prepend_sys_path = .
|
||||
version_path_separator = os
|
||||
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||
version_locations = %(here)s/alembic/versions
|
||||
|
||||
[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
|
49
alembic/env.py
Normal file
49
alembic/env.py
Normal file
@ -0,0 +1,49 @@
|
||||
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"}
|
39
alembic/versions/001_initial_task_table.py
Normal file
39
alembic/versions/001_initial_task_table.py
Normal file
@ -0,0 +1,39 @@
|
||||
"""Create initial task table
|
||||
|
||||
Revision ID: 001
|
||||
Revises:
|
||||
Create Date: 2024-01-01 00: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("completed", sa.Boolean(), nullable=False),
|
||||
sa.Column("priority", sa.String(length=10), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("due_date", sa.DateTime(), 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")
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
51
app/api/tasks.py
Normal file
51
app/api/tasks.py
Normal file
@ -0,0 +1,51 @@
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from app.db.session import get_db
|
||||
from app.crud import task_crud
|
||||
from app.schemas.task import TaskCreate, TaskUpdate, TaskResponse
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/tasks", response_model=TaskResponse, status_code=201)
|
||||
def create_task(task: TaskCreate, db: Session = Depends(get_db)):
|
||||
return task_crud.create_task(db=db, task=task)
|
||||
|
||||
|
||||
@router.get("/tasks", response_model=List[TaskResponse])
|
||||
def get_tasks(
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(100, ge=1, le=1000),
|
||||
completed: Optional[bool] = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
return task_crud.get_tasks(db=db, skip=skip, limit=limit, completed=completed)
|
||||
|
||||
|
||||
@router.get("/tasks/{task_id}", response_model=TaskResponse)
|
||||
def get_task(task_id: int, db: Session = Depends(get_db)):
|
||||
db_task = task_crud.get_task(db=db, task_id=task_id)
|
||||
if not db_task:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return db_task
|
||||
|
||||
|
||||
@router.put("/tasks/{task_id}", response_model=TaskResponse)
|
||||
def update_task(task_id: int, task_update: TaskUpdate, db: Session = Depends(get_db)):
|
||||
db_task = task_crud.update_task(db=db, task_id=task_id, task_update=task_update)
|
||||
if not db_task:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return db_task
|
||||
|
||||
|
||||
@router.delete("/tasks/{task_id}", status_code=204)
|
||||
def delete_task(task_id: int, db: Session = Depends(get_db)):
|
||||
success = task_crud.delete_task(db=db, task_id=task_id)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
|
||||
|
||||
@router.get("/tasks/priority/{priority}", response_model=List[TaskResponse])
|
||||
def get_tasks_by_priority(priority: str, db: Session = Depends(get_db)):
|
||||
return task_crud.get_tasks_by_priority(db=db, priority=priority)
|
58
app/crud.py
Normal file
58
app/crud.py
Normal file
@ -0,0 +1,58 @@
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.task import Task
|
||||
from app.schemas.task import TaskCreate, TaskUpdate
|
||||
|
||||
|
||||
class TaskCRUD:
|
||||
def create_task(self, db: Session, task: TaskCreate) -> Task:
|
||||
db_task = Task(**task.model_dump())
|
||||
db.add(db_task)
|
||||
db.commit()
|
||||
db.refresh(db_task)
|
||||
return db_task
|
||||
|
||||
def get_task(self, db: Session, task_id: int) -> Optional[Task]:
|
||||
return db.query(Task).filter(Task.id == task_id).first()
|
||||
|
||||
def get_tasks(
|
||||
self,
|
||||
db: Session,
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
completed: Optional[bool] = None,
|
||||
) -> List[Task]:
|
||||
query = db.query(Task)
|
||||
if completed is not None:
|
||||
query = query.filter(Task.completed == completed)
|
||||
return query.offset(skip).limit(limit).all()
|
||||
|
||||
def update_task(
|
||||
self, db: Session, task_id: int, task_update: TaskUpdate
|
||||
) -> Optional[Task]:
|
||||
db_task = self.get_task(db, task_id)
|
||||
if not db_task:
|
||||
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(self, db: Session, task_id: int) -> bool:
|
||||
db_task = self.get_task(db, task_id)
|
||||
if not db_task:
|
||||
return False
|
||||
|
||||
db.delete(db_task)
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
def get_tasks_by_priority(self, db: Session, priority: str) -> List[Task]:
|
||||
return db.query(Task).filter(Task.priority == priority).all()
|
||||
|
||||
|
||||
task_crud = TaskCRUD()
|
0
app/db/__init__.py
Normal file
0
app/db/__init__.py
Normal file
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()
|
0
app/models/__init__.py
Normal file
0
app/models/__init__.py
Normal file
18
app/models/task.py
Normal file
18
app/models/task.py
Normal file
@ -0,0 +1,18 @@
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
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)
|
||||
completed = Column(Boolean, default=False, nullable=False)
|
||||
priority = Column(String(10), default="medium", nullable=False)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = Column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
)
|
||||
due_date = Column(DateTime, nullable=True)
|
0
app/schemas/__init__.py
Normal file
0
app/schemas/__init__.py
Normal file
32
app/schemas/task.py
Normal file
32
app/schemas/task.py
Normal file
@ -0,0 +1,32 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class TaskBase(BaseModel):
|
||||
title: str
|
||||
description: Optional[str] = None
|
||||
completed: bool = False
|
||||
priority: str = "medium"
|
||||
due_date: Optional[datetime] = None
|
||||
|
||||
|
||||
class TaskCreate(TaskBase):
|
||||
pass
|
||||
|
||||
|
||||
class TaskUpdate(BaseModel):
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
completed: Optional[bool] = None
|
||||
priority: Optional[str] = None
|
||||
due_date: Optional[datetime] = None
|
||||
|
||||
|
||||
class TaskResponse(TaskBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
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.api.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",
|
||||
openapi_url="/openapi.json",
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(tasks_router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async 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")
|
||||
async 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
|
||||
python-multipart==0.0.6
|
||||
pydantic==2.5.0
|
||||
ruff==0.1.6
|
Loading…
x
Reference in New Issue
Block a user