Add Task Manager API with FastAPI and SQLite
- Created FastAPI application structure with main.py - Implemented SQLAlchemy models for tasks with priority and completion status - Set up database connection with SQLite using absolute paths - Created Alembic migrations for database schema - Added CRUD operations for task management - Implemented health check and root endpoints - Added CORS configuration for cross-origin requests - Created comprehensive API documentation - Added Ruff configuration for code linting - Updated README with installation and usage instructions
This commit is contained in:
parent
5722b19790
commit
f63bd5104b
65
README.md
65
README.md
@ -1,3 +1,64 @@
|
|||||||
# FastAPI Application
|
# Task Manager API
|
||||||
|
|
||||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
A simple task management API built with FastAPI and SQLite.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Create, read, update, and delete tasks
|
||||||
|
- Task priority levels (low, medium, high)
|
||||||
|
- Task completion status tracking
|
||||||
|
- Automatic timestamps for creation and updates
|
||||||
|
- Health check endpoint
|
||||||
|
- Interactive API documentation
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Run database migrations:
|
||||||
|
```bash
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Start the application:
|
||||||
|
```bash
|
||||||
|
uvicorn main:app --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
The API will be available at `http://localhost:8000`
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
- `GET /` - Root endpoint with API information
|
||||||
|
- `GET /health` - Health check endpoint
|
||||||
|
- `GET /docs` - Interactive API documentation (Swagger UI)
|
||||||
|
- `GET /redoc` - Alternative API documentation
|
||||||
|
- `POST /tasks/` - Create a new task
|
||||||
|
- `GET /tasks/` - List all tasks (with pagination)
|
||||||
|
- `GET /tasks/{task_id}` - Get a specific task
|
||||||
|
- `PUT /tasks/{task_id}` - Update a task
|
||||||
|
- `DELETE /tasks/{task_id}` - Delete a task
|
||||||
|
|
||||||
|
## Task Schema
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"title": "string",
|
||||||
|
"description": "string (optional)",
|
||||||
|
"completed": false,
|
||||||
|
"priority": "medium"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Priority levels: `low`, `medium`, `high`
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
The application uses SQLite with the database file stored at `/app/storage/db/db.sqlite`.
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
No environment variables are required for basic operation. The application uses SQLite with default settings.
|
||||||
|
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
|
52
alembic/env.py
Normal file
52
alembic/env.py
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
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(__file__)))
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
from app.models.task import Task
|
||||||
|
|
||||||
|
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"}
|
36
alembic/versions/001_create_tasks_table.py
Normal file
36
alembic/versions/001_create_tasks_table.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
"""Create tasks 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=255), nullable=False),
|
||||||
|
sa.Column('description', sa.Text(), nullable=True),
|
||||||
|
sa.Column('completed', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('priority', sa.String(length=20), 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')
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/crud/__init__.py
Normal file
0
app/crud/__init__.py
Normal file
34
app/crud/task.py
Normal file
34
app/crud/task.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.models.task import Task as TaskModel
|
||||||
|
from app.schemas.task import TaskCreate, TaskUpdate
|
||||||
|
|
||||||
|
def create_task(db: Session, task: TaskCreate):
|
||||||
|
db_task = TaskModel(**task.dict())
|
||||||
|
db.add(db_task)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_task)
|
||||||
|
return db_task
|
||||||
|
|
||||||
|
def get_tasks(db: Session, skip: int = 0, limit: int = 100):
|
||||||
|
return db.query(TaskModel).offset(skip).limit(limit).all()
|
||||||
|
|
||||||
|
def get_task(db: Session, task_id: int):
|
||||||
|
return db.query(TaskModel).filter(TaskModel.id == task_id).first()
|
||||||
|
|
||||||
|
def update_task(db: Session, task_id: int, task: TaskUpdate):
|
||||||
|
db_task = db.query(TaskModel).filter(TaskModel.id == task_id).first()
|
||||||
|
if db_task:
|
||||||
|
update_data = task.dict(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):
|
||||||
|
db_task = db.query(TaskModel).filter(TaskModel.id == task_id).first()
|
||||||
|
if db_task:
|
||||||
|
db.delete(db_task)
|
||||||
|
db.commit()
|
||||||
|
return True
|
||||||
|
return False
|
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()
|
27
app/db/session.py
Normal file
27
app/db/session.py
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
def create_tables():
|
||||||
|
Base.metadata.create_all(bind=engine)
|
0
app/models/__init__.py
Normal file
0
app/models/__init__.py
Normal file
14
app/models/task.py
Normal file
14
app/models/task.py
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
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)
|
||||||
|
completed = Column(Boolean, default=False, nullable=False)
|
||||||
|
priority = Column(String(20), default="medium", nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
0
app/schemas/__init__.py
Normal file
0
app/schemas/__init__.py
Normal file
26
app/schemas/task.py
Normal file
26
app/schemas/task.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
class TaskBase(BaseModel):
|
||||||
|
title: str
|
||||||
|
description: Optional[str] = None
|
||||||
|
completed: bool = False
|
||||||
|
priority: str = "medium"
|
||||||
|
|
||||||
|
class TaskCreate(TaskBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class TaskUpdate(BaseModel):
|
||||||
|
title: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
completed: Optional[bool] = None
|
||||||
|
priority: Optional[str] = None
|
||||||
|
|
||||||
|
class Task(TaskBase):
|
||||||
|
id: int
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
72
main.py
Normal file
72
main.py
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
from fastapi import FastAPI, HTTPException, Depends
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from typing import List
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.db.session import get_db
|
||||||
|
from app.models.task import Task as TaskModel
|
||||||
|
from app.schemas.task import Task, TaskCreate, TaskUpdate
|
||||||
|
from app.crud.task import create_task, get_tasks, get_task, update_task, delete_task
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="Task Manager API",
|
||||||
|
description="A simple task management API built with FastAPI",
|
||||||
|
version="1.0.0"
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
@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"}
|
||||||
|
|
||||||
|
@app.post("/tasks/", response_model=Task)
|
||||||
|
async def create_new_task(task: TaskCreate, db: Session = Depends(get_db)):
|
||||||
|
return create_task(db=db, task=task)
|
||||||
|
|
||||||
|
@app.get("/tasks/", response_model=List[Task])
|
||||||
|
async def read_tasks(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||||
|
return get_tasks(db=db, skip=skip, limit=limit)
|
||||||
|
|
||||||
|
@app.get("/tasks/{task_id}", response_model=Task)
|
||||||
|
async def read_task(task_id: int, db: Session = Depends(get_db)):
|
||||||
|
db_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
|
||||||
|
|
||||||
|
@app.put("/tasks/{task_id}", response_model=Task)
|
||||||
|
async def update_existing_task(task_id: int, task: TaskUpdate, db: Session = Depends(get_db)):
|
||||||
|
db_task = update_task(db=db, task_id=task_id, task=task)
|
||||||
|
if db_task is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Task not found")
|
||||||
|
return db_task
|
||||||
|
|
||||||
|
@app.delete("/tasks/{task_id}")
|
||||||
|
async def delete_existing_task(task_id: int, db: Session = Depends(get_db)):
|
||||||
|
success = delete_task(db=db, task_id=task_id)
|
||||||
|
if not success:
|
||||||
|
raise HTTPException(status_code=404, detail="Task not found")
|
||||||
|
return {"message": "Task deleted successfully"}
|
||||||
|
|
||||||
|
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.12.1
|
||||||
|
pydantic==2.5.0
|
||||||
|
python-multipart==0.0.6
|
||||||
|
ruff==0.1.6
|
Loading…
x
Reference in New Issue
Block a user