Implement Task Manager API with FastAPI and SQLite
- Created FastAPI application structure with main.py and requirements.txt - Setup SQLite database with SQLAlchemy models for tasks - Implemented Alembic migrations for database schema management - Added CRUD endpoints for task management (GET, POST, PUT, DELETE) - Configured CORS middleware to allow all origins - Added health endpoint and base route with API information - Updated README with comprehensive documentation - Applied code formatting with Ruff linter
This commit is contained in:
parent
655f70943e
commit
d09d61a7c8
94
README.md
94
README.md
@ -1,3 +1,93 @@
|
||||
# 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 (high, medium, low)
|
||||
- Task completion status tracking
|
||||
- RESTful API design
|
||||
- Automatic API documentation with Swagger UI
|
||||
|
||||
## Quick Start
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
4. Open your browser and navigate to:
|
||||
- API Documentation: http://localhost:8000/docs
|
||||
- Alternative Documentation: http://localhost:8000/redoc
|
||||
- Health Check: http://localhost:8000/health
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Base Routes
|
||||
- `GET /` - API information and links
|
||||
- `GET /health` - Health check endpoint
|
||||
|
||||
### Task Management
|
||||
- `GET /api/v1/tasks` - Get all tasks (with pagination)
|
||||
- `GET /api/v1/tasks/{id}` - Get a specific task
|
||||
- `POST /api/v1/tasks` - Create a new task
|
||||
- `PUT /api/v1/tasks/{id}` - Update a task
|
||||
- `DELETE /api/v1/tasks/{id}` - Delete a task
|
||||
|
||||
## Task Schema
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "string",
|
||||
"description": "string (optional)",
|
||||
"completed": "boolean (default: false)",
|
||||
"priority": "string (default: medium)",
|
||||
"id": "integer (auto-generated)",
|
||||
"created_at": "datetime (auto-generated)",
|
||||
"updated_at": "datetime (auto-generated)"
|
||||
}
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
├── main.py # FastAPI application entry point
|
||||
├── requirements.txt # Python dependencies
|
||||
├── alembic.ini # Alembic configuration
|
||||
├── alembic/ # Database migrations
|
||||
├── app/
|
||||
│ ├── db/
|
||||
│ │ ├── base.py # SQLAlchemy Base
|
||||
│ │ └── session.py # Database session management
|
||||
│ ├── models/
|
||||
│ │ └── task.py # Task SQLAlchemy model
|
||||
│ ├── routers/
|
||||
│ │ └── tasks.py # Task API endpoints
|
||||
│ └── schemas/
|
||||
│ └── task.py # Pydantic schemas
|
||||
└── storage/
|
||||
└── db/ # SQLite database storage
|
||||
```
|
||||
|
||||
## Database
|
||||
|
||||
The application uses SQLite for data storage. The database file is created automatically at `/app/storage/db/db.sqlite`.
|
||||
|
||||
## Development
|
||||
|
||||
The application is configured with:
|
||||
- CORS enabled for all origins
|
||||
- Automatic API documentation
|
||||
- Database migrations with Alembic
|
||||
- Pydantic models for request/response validation
|
||||
|
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.stdout,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
51
alembic/env.py
Normal file
51
alembic/env.py
Normal file
@ -0,0 +1,51 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from logging.config import fileConfig
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
from alembic import context
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
|
||||
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"}
|
36
alembic/versions/001_initial_task_table.py
Normal file
36
alembic/versions/001_initial_task_table.py
Normal file
@ -0,0 +1,36 @@
|
||||
"""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=20), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index('ix_tasks_id', 'tasks', ['id'], unique=False)
|
||||
op.create_index('ix_tasks_title', 'tasks', ['title'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index('ix_tasks_title', table_name='tasks')
|
||||
op.drop_index('ix_tasks_id', table_name='tasks')
|
||||
op.drop_table('tasks')
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
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
14
app/models/task.py
Normal file
14
app/models/task.py
Normal file
@ -0,0 +1,14 @@
|
||||
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(20), 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)
|
0
app/routers/__init__.py
Normal file
0
app/routers/__init__.py
Normal file
52
app/routers/tasks.py
Normal file
52
app/routers/tasks.py
Normal file
@ -0,0 +1,52 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.db.session import get_db
|
||||
from app.models.task import Task
|
||||
from app.schemas.task import Task as TaskSchema, TaskCreate, TaskUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/tasks", response_model=List[TaskSchema])
|
||||
def get_tasks(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||
tasks = db.query(Task).offset(skip).limit(limit).all()
|
||||
return tasks
|
||||
|
||||
@router.get("/tasks/{task_id}", response_model=TaskSchema)
|
||||
def get_task(task_id: int, db: Session = Depends(get_db)):
|
||||
task = db.query(Task).filter(Task.id == task_id).first()
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return task
|
||||
|
||||
@router.post("/tasks", response_model=TaskSchema)
|
||||
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.put("/tasks/{task_id}", response_model=TaskSchema)
|
||||
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 task is None:
|
||||
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("/tasks/{task_id}")
|
||||
def delete_task(task_id: int, db: Session = Depends(get_db)):
|
||||
task = db.query(Task).filter(Task.id == task_id).first()
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
|
||||
db.delete(task)
|
||||
db.commit()
|
||||
return {"message": "Task deleted successfully"}
|
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 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"
|
||||
|
||||
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
|
38
main.py
Normal file
38
main.py
Normal file
@ -0,0 +1,38 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.routers import tasks
|
||||
|
||||
app = FastAPI(
|
||||
title="Task Manager API",
|
||||
description="A simple task management API built with FastAPI",
|
||||
version="1.0.0",
|
||||
openapi_url="/openapi.json"
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(tasks.router, prefix="/api/v1", tags=["tasks"])
|
||||
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
return {
|
||||
"title": "Task Manager API",
|
||||
"description": "A simple task management API built with FastAPI",
|
||||
"version": "1.0.0",
|
||||
"documentation": "/docs",
|
||||
"health": "/health"
|
||||
}
|
||||
|
||||
@app.get("/health")
|
||||
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