Implement Task Manager API
- Set up FastAPI application structure - Create Task model with SQLAlchemy - Implement CRUD operations for tasks - Add API endpoints for tasks with filtering options - Configure Alembic for database migrations - Add health check endpoint - Configure Ruff for linting - Add comprehensive documentation in README.md
This commit is contained in:
parent
55326b462b
commit
53bc4e0199
118
README.md
118
README.md
@ -1,3 +1,117 @@
|
||||
# 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 title, priority, and completion status
|
||||
- Pagination support
|
||||
- Health check endpoint
|
||||
- SQLite database with SQLAlchemy ORM
|
||||
- Alembic for database migrations
|
||||
- Comprehensive API documentation with Swagger UI
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Python 3.8+
|
||||
- pip
|
||||
|
||||
### Installation
|
||||
|
||||
1. Clone the repository
|
||||
2. Install dependencies:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Run database migrations:
|
||||
|
||||
```bash
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
4. Start the application:
|
||||
|
||||
```bash
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
The API will be available at `http://localhost:8000`
|
||||
|
||||
- API Documentation: `http://localhost:8000/docs` or `http://localhost:8000/redoc`
|
||||
- OpenAPI Schema: `http://localhost:8000/openapi.json`
|
||||
- Health Check: `http://localhost:8000/health`
|
||||
|
||||
### Tasks Endpoints
|
||||
|
||||
- `GET /api/v1/tasks`: List all tasks (with optional filtering)
|
||||
- `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
|
||||
|
||||
### Query Parameters for Filtering Tasks
|
||||
|
||||
- `skip`: Number of tasks to skip (pagination)
|
||||
- `limit`: Maximum number of tasks to return (pagination)
|
||||
- `title`: Filter by title (partial match)
|
||||
- `priority`: Filter by priority (1=Low, 2=Medium, 3=High)
|
||||
- `completed`: Filter by completion status (true/false)
|
||||
|
||||
## Task Data Model
|
||||
|
||||
- `id`: Unique identifier
|
||||
- `title`: Task title (required)
|
||||
- `description`: Task description (optional)
|
||||
- `completed`: Completion status (default: false)
|
||||
- `priority`: Priority level (1=Low, 2=Medium, 3=High, default: 1)
|
||||
- `due_date`: Due date (optional)
|
||||
- `created_at`: Creation timestamp
|
||||
- `updated_at`: Last update timestamp
|
||||
|
||||
## Development
|
||||
|
||||
### Project Structure
|
||||
|
||||
```
|
||||
.
|
||||
├── alembic.ini # Alembic configuration file
|
||||
├── main.py # FastAPI application entry point
|
||||
├── README.md # Project documentation
|
||||
├── requirements.txt # Project dependencies
|
||||
├── app/ # Application package
|
||||
│ ├── api/ # API endpoints
|
||||
│ │ └── v1/ # API version 1
|
||||
│ │ └── endpoints/ # API endpoints modules
|
||||
│ ├── core/ # Core application modules
|
||||
│ ├── crud/ # CRUD operations
|
||||
│ ├── db/ # Database setup and session
|
||||
│ ├── models/ # SQLAlchemy models
|
||||
│ └── schemas/ # Pydantic schemas
|
||||
└── migrations/ # Alembic migrations
|
||||
└── versions/ # Migration versions
|
||||
```
|
||||
|
||||
### Database Migrations
|
||||
|
||||
To create a new migration after model changes:
|
||||
|
||||
```bash
|
||||
alembic revision --autogenerate -m "description"
|
||||
```
|
||||
|
||||
To apply migrations:
|
||||
|
||||
```bash
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License.
|
105
alembic.ini
Normal file
105
alembic.ini
Normal file
@ -0,0 +1,105 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = migrations
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the python-dateutil library that can be
|
||||
# installed by adding `alembic[tz]` to the pip requirements
|
||||
# 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.
|
||||
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
|
||||
|
||||
# version path separator; As mentioned above, this is the character used to split
|
||||
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||
# Valid values for version_path_separator are:
|
||||
#
|
||||
# version_path_separator = :
|
||||
# version_path_separator = ;
|
||||
# version_path_separator = space
|
||||
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||
|
||||
# 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 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# 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
|
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Task Manager API application package."""
|
1
app/api/v1/__init__.py
Normal file
1
app/api/v1/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""API v1 package."""
|
7
app/api/v1/api.py
Normal file
7
app/api/v1/api.py
Normal file
@ -0,0 +1,7 @@
|
||||
"""API router setup."""
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.v1.endpoints import tasks
|
||||
|
||||
api_router = APIRouter(prefix="/api/v1")
|
||||
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])
|
1
app/api/v1/endpoints/__init__.py
Normal file
1
app/api/v1/endpoints/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""API endpoints package."""
|
103
app/api/v1/endpoints/tasks.py
Normal file
103
app/api/v1/endpoints/tasks.py
Normal file
@ -0,0 +1,103 @@
|
||||
"""Task endpoints."""
|
||||
from typing import Any, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import crud, schemas
|
||||
from app.db.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/", response_model=List[schemas.TaskResponse])
|
||||
def read_tasks(
|
||||
db: Session = Depends(get_db),
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
title: Optional[str] = None,
|
||||
priority: Optional[int] = None,
|
||||
completed: Optional[bool] = None,
|
||||
) -> Any:
|
||||
"""
|
||||
Retrieve tasks.
|
||||
|
||||
- **skip**: Number of tasks to skip (pagination)
|
||||
- **limit**: Maximum number of tasks to return (pagination)
|
||||
- **title**: Filter by title (partial match)
|
||||
- **priority**: Filter by priority (1=Low, 2=Medium, 3=High)
|
||||
- **completed**: Filter by completion status
|
||||
"""
|
||||
if title is not None:
|
||||
return crud.task.get_by_title(db, title=title)
|
||||
if priority is not None:
|
||||
return crud.task.get_by_priority(db, priority=priority, skip=skip, limit=limit)
|
||||
if completed is not None:
|
||||
if completed:
|
||||
return crud.task.get_completed(db, skip=skip, limit=limit)
|
||||
else:
|
||||
# Get incomplete tasks
|
||||
return db.query(crud.task.model).filter(
|
||||
crud.task.model.completed == False # noqa: E712
|
||||
).offset(skip).limit(limit).all()
|
||||
return crud.task.get_multi(db, skip=skip, limit=limit)
|
||||
|
||||
|
||||
@router.post("/", response_model=schemas.TaskResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_task(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_in: schemas.TaskCreate,
|
||||
) -> Any:
|
||||
"""Create new task."""
|
||||
return crud.task.create(db=db, obj_in=task_in)
|
||||
|
||||
|
||||
@router.get("/{task_id}", response_model=schemas.TaskResponse)
|
||||
def read_task(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_id: int,
|
||||
) -> Any:
|
||||
"""Get task by ID."""
|
||||
task = crud.task.get(db=db, id=task_id)
|
||||
if not task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Task not found",
|
||||
)
|
||||
return task
|
||||
|
||||
|
||||
@router.put("/{task_id}", response_model=schemas.TaskResponse)
|
||||
def update_task(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_id: int,
|
||||
task_in: schemas.TaskUpdate,
|
||||
) -> Any:
|
||||
"""Update a task."""
|
||||
task = crud.task.get(db=db, id=task_id)
|
||||
if not task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Task not found",
|
||||
)
|
||||
return crud.task.update(db=db, db_obj=task, obj_in=task_in)
|
||||
|
||||
|
||||
@router.delete("/{task_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||
def delete_task(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_id: int,
|
||||
) -> None:
|
||||
"""Delete a task."""
|
||||
task = crud.task.get(db=db, id=task_id)
|
||||
if not task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Task not found",
|
||||
)
|
||||
crud.task.remove(db=db, id=task_id)
|
||||
return None
|
1
app/core/__init__.py
Normal file
1
app/core/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Core package."""
|
25
app/core/config.py
Normal file
25
app/core/config.py
Normal file
@ -0,0 +1,25 @@
|
||||
"""Application configuration settings."""
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""Application settings."""
|
||||
PROJECT_NAME: str = "Task Manager API"
|
||||
PROJECT_DESCRIPTION: str = "A FastAPI-based Task Manager API"
|
||||
VERSION: str = "0.1.0"
|
||||
API_V1_STR: str = "/api/v1"
|
||||
|
||||
# Database
|
||||
DB_DIR = Path("/app") / "storage" / "db"
|
||||
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||
|
||||
class Config:
|
||||
"""Config class for Settings."""
|
||||
case_sensitive = True
|
||||
env_file = ".env"
|
||||
|
||||
|
||||
settings = Settings()
|
4
app/crud/__init__.py
Normal file
4
app/crud/__init__.py
Normal file
@ -0,0 +1,4 @@
|
||||
"""CRUD operations package."""
|
||||
from app.crud.task import task
|
||||
|
||||
__all__ = ["task"]
|
66
app/crud/base.py
Normal file
66
app/crud/base.py
Normal file
@ -0,0 +1,66 @@
|
||||
"""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 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 a record 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 records."""
|
||||
return db.query(self.model).offset(skip).limit(limit).all()
|
||||
|
||||
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
|
||||
"""Create a new record."""
|
||||
obj_in_data = jsonable_encoder(obj_in)
|
||||
db_obj = self.model(**obj_in_data)
|
||||
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 a record."""
|
||||
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 a record."""
|
||||
obj = db.query(self.model).get(id)
|
||||
db.delete(obj)
|
||||
db.commit()
|
||||
return obj
|
28
app/crud/task.py
Normal file
28
app/crud/task.py
Normal file
@ -0,0 +1,28 @@
|
||||
"""Task CRUD operations."""
|
||||
from typing import List
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud.base import CRUDBase
|
||||
from app.models.task import Task
|
||||
from app.schemas.task import TaskCreate, TaskUpdate
|
||||
|
||||
|
||||
class CRUDTask(CRUDBase[Task, TaskCreate, TaskUpdate]):
|
||||
"""CRUD operations for tasks."""
|
||||
def get_by_title(self, db: Session, *, title: str) -> List[Task]:
|
||||
"""Get tasks by title (partial match)."""
|
||||
return db.query(Task).filter(Task.title.like(f"%{title}%")).all()
|
||||
|
||||
def get_completed(self, db: Session, *, skip: int = 0, limit: int = 100) -> List[Task]:
|
||||
"""Get completed tasks."""
|
||||
return db.query(Task).filter(Task.completed == True).offset(skip).limit(limit).all() # noqa: E712
|
||||
|
||||
def get_by_priority(
|
||||
self, db: Session, *, priority: int, skip: int = 0, limit: int = 100
|
||||
) -> List[Task]:
|
||||
"""Get tasks by priority."""
|
||||
return db.query(Task).filter(Task.priority == priority).offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
task = CRUDTask(Task)
|
1
app/db/__init__.py
Normal file
1
app/db/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Database package."""
|
4
app/db/base.py
Normal file
4
app/db/base.py
Normal file
@ -0,0 +1,4 @@
|
||||
"""SQLAlchemy base model definition."""
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
Base = declarative_base()
|
7
app/db/base_class.py
Normal file
7
app/db/base_class.py
Normal file
@ -0,0 +1,7 @@
|
||||
"""Base class for all models."""
|
||||
from app.db.base import Base
|
||||
|
||||
# Import all models here so that Base has them before creating the metadata
|
||||
from app.models.task import Task
|
||||
|
||||
__all__ = ["Base", "Task"]
|
20
app/db/session.py
Normal file
20
app/db/session.py
Normal file
@ -0,0 +1,20 @@
|
||||
"""Database session and engine setup."""
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_engine(
|
||||
settings.SQLALCHEMY_DATABASE_URL,
|
||||
connect_args={"check_same_thread": False}
|
||||
)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db():
|
||||
"""Get database session."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
4
app/models/__init__.py
Normal file
4
app/models/__init__.py
Normal file
@ -0,0 +1,4 @@
|
||||
"""SQLAlchemy models package."""
|
||||
from app.models.task import Task
|
||||
|
||||
__all__ = ["Task"]
|
19
app/models/task.py
Normal file
19
app/models/task.py
Normal file
@ -0,0 +1,19 @@
|
||||
"""Task model definition."""
|
||||
from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class Task(Base):
|
||||
"""Task model for the tasks table."""
|
||||
__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)
|
||||
priority = Column(Integer, default=1) # 1=Low, 2=Medium, 3=High
|
||||
due_date = Column(DateTime, nullable=True)
|
||||
created_at = Column(DateTime, server_default=func.now())
|
||||
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
4
app/schemas/__init__.py
Normal file
4
app/schemas/__init__.py
Normal file
@ -0,0 +1,4 @@
|
||||
"""Pydantic schemas package."""
|
||||
from app.schemas.task import Task, TaskCreate, TaskResponse, TaskUpdate
|
||||
|
||||
__all__ = ["Task", "TaskCreate", "TaskUpdate", "TaskResponse"]
|
48
app/schemas/task.py
Normal file
48
app/schemas/task.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""Task schemas for request/response validation."""
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class TaskBase(BaseModel):
|
||||
"""Base schema for Task."""
|
||||
title: str = Field(..., min_length=1, max_length=255, description="Title of the task")
|
||||
description: Optional[str] = Field(None, description="Description of the task")
|
||||
completed: bool = Field(False, description="Completion status of the task")
|
||||
priority: int = Field(1, ge=1, le=3, description="Priority level: 1=Low, 2=Medium, 3=High")
|
||||
due_date: Optional[datetime] = Field(None, description="Due date of the task")
|
||||
|
||||
|
||||
class TaskCreate(TaskBase):
|
||||
"""Schema for creating a new task."""
|
||||
pass
|
||||
|
||||
|
||||
class TaskUpdate(BaseModel):
|
||||
"""Schema for updating an existing task."""
|
||||
title: Optional[str] = Field(
|
||||
None, min_length=1, max_length=255, description="Title of the task"
|
||||
)
|
||||
description: Optional[str] = Field(None, description="Description of the task")
|
||||
completed: Optional[bool] = Field(None, description="Completion status of the task")
|
||||
priority: Optional[int] = Field(
|
||||
None, ge=1, le=3, description="Priority level: 1=Low, 2=Medium, 3=High"
|
||||
)
|
||||
due_date: Optional[datetime] = Field(None, description="Due date of the task")
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class Task(TaskBase):
|
||||
"""Schema for Task model."""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class TaskResponse(Task):
|
||||
"""Schema for Task response."""
|
||||
pass
|
48
main.py
Normal file
48
main.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""Task Manager API main application file."""
|
||||
import uvicorn
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api.v1.api import api_router
|
||||
from app.core.config import settings
|
||||
|
||||
app = FastAPI(
|
||||
title=settings.PROJECT_NAME,
|
||||
description=settings.PROJECT_DESCRIPTION,
|
||||
version=settings.VERSION,
|
||||
openapi_url="/openapi.json",
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
)
|
||||
|
||||
# Configure CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Include API router
|
||||
app.include_router(api_router)
|
||||
|
||||
|
||||
@app.get("/", tags=["Root"])
|
||||
async def root():
|
||||
"""Root endpoint that returns basic information about the API."""
|
||||
return {
|
||||
"title": settings.PROJECT_NAME,
|
||||
"docs": "/docs",
|
||||
"health": "/health",
|
||||
}
|
||||
|
||||
|
||||
@app.get("/health", tags=["Health"])
|
||||
async def health_check():
|
||||
"""Health check endpoint."""
|
||||
return {"status": "healthy"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
1
migrations/README
Normal file
1
migrations/README
Normal file
@ -0,0 +1 @@
|
||||
Generic single-database configuration for Alembic.
|
90
migrations/env.py
Normal file
90
migrations/env.py
Normal file
@ -0,0 +1,90 @@
|
||||
"""Alembic environment configuration."""
|
||||
import os
|
||||
import sys
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
# Add the project root directory to the Python path
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
||||
|
||||
# Import the SQLAlchemy metadata and models
|
||||
from app.db.base_class import Base # noqa
|
||||
from app.core.config import settings # noqa
|
||||
|
||||
# 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.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# Set the SQLAlchemy URL
|
||||
config.set_main_option("sqlalchemy.url", settings.SQLALCHEMY_DATABASE_URL)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
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() -> None:
|
||||
"""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() -> None:
|
||||
"""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
24
migrations/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"}
|
43
migrations/versions/00000000000_create_tasks_table.py
Normal file
43
migrations/versions/00000000000_create_tasks_table.py
Normal file
@ -0,0 +1,43 @@
|
||||
"""create tasks table.
|
||||
|
||||
Revision ID: 00000000000
|
||||
Revises:
|
||||
Create Date: 2023-10-01 00:00:00.000000
|
||||
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '00000000000'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Create tasks table."""
|
||||
op.create_table(
|
||||
'tasks',
|
||||
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('completed', sa.Boolean(), default=False),
|
||||
sa.Column('priority', sa.Integer(), default=1),
|
||||
sa.Column('due_date', sa.DateTime(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),
|
||||
sa.Column(
|
||||
'updated_at',
|
||||
sa.DateTime(),
|
||||
server_default=sa.func.now(),
|
||||
onupdate=sa.func.now()
|
||||
),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index(op.f('ix_tasks_id'), 'tasks', ['id'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Drop tasks table."""
|
||||
op.drop_index(op.f('ix_tasks_id'), table_name='tasks')
|
||||
op.drop_table('tasks')
|
31
pyproject.toml
Normal file
31
pyproject.toml
Normal file
@ -0,0 +1,31 @@
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
|
||||
[tool.ruff.lint]
|
||||
# Enable pycodestyle (E), Pyflakes (F), isort (I), and pydocstyle (D)
|
||||
select = ["E", "F", "I", "D"]
|
||||
ignore = ["D203", "D212"]
|
||||
|
||||
# Allow autofix for all enabled rules
|
||||
fixable = ["A", "B", "C", "D", "E", "F", "I"]
|
||||
unfixable = []
|
||||
|
||||
# Exclude a variety of commonly ignored directories
|
||||
exclude = [
|
||||
".git",
|
||||
".ruff_cache",
|
||||
"__pycache__",
|
||||
"migrations",
|
||||
"venv",
|
||||
".env",
|
||||
".venv",
|
||||
]
|
||||
|
||||
# Allow unused variables when underscore-prefixed
|
||||
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
known-first-party = ["app"]
|
||||
|
||||
[tool.ruff.lint.pydocstyle]
|
||||
convention = "google"
|
8
requirements.txt
Normal file
8
requirements.txt
Normal file
@ -0,0 +1,8 @@
|
||||
fastapi>=0.103.1,<0.104.0
|
||||
uvicorn>=0.23.2,<0.24.0
|
||||
sqlalchemy>=2.0.20,<2.1.0
|
||||
alembic>=1.12.0,<1.13.0
|
||||
pydantic>=2.3.0,<2.4.0
|
||||
pydantic-settings>=2.0.3,<2.1.0
|
||||
ruff>=0.0.290,<0.1.0
|
||||
python-dotenv>=1.0.0,<1.1.0
|
Loading…
x
Reference in New Issue
Block a user