Build complete Personal Task Management API with FastAPI
- Implemented user authentication with JWT tokens - Created comprehensive task management with CRUD operations - Added category system for task organization - Set up SQLite database with SQLAlchemy ORM - Configured Alembic for database migrations - Added API documentation with OpenAPI/Swagger - Implemented proper authorization and user scoping - Created health check and root endpoints - Updated README with complete documentation
This commit is contained in:
parent
8f91e1e349
commit
f19a6fea04
155
README.md
155
README.md
@ -1,3 +1,154 @@
|
|||||||
# FastAPI Application
|
# Personal Task Management API
|
||||||
|
|
||||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
A comprehensive FastAPI-based REST API for managing personal tasks, categories, and user authentication. Built with Python, FastAPI, SQLAlchemy, and SQLite.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **User Authentication**: JWT-based authentication with registration and login
|
||||||
|
- **Task Management**: Full CRUD operations for tasks with status and priority tracking
|
||||||
|
- **Category Management**: Organize tasks with custom categories
|
||||||
|
- **User Authorization**: All operations are user-scoped and protected
|
||||||
|
- **Database Migrations**: Alembic for database schema management
|
||||||
|
- **API Documentation**: Auto-generated OpenAPI/Swagger documentation
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Python 3.8+
|
||||||
|
- pip
|
||||||
|
|
||||||
|
### 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 Documentation
|
||||||
|
|
||||||
|
- Swagger UI: `http://localhost:8000/docs`
|
||||||
|
- ReDoc: `http://localhost:8000/redoc`
|
||||||
|
- OpenAPI JSON: `http://localhost:8000/openapi.json`
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### Authentication
|
||||||
|
- `POST /auth/register` - Register a new user
|
||||||
|
- `POST /auth/login` - Login with email and password
|
||||||
|
- `GET /auth/me` - Get current user information
|
||||||
|
|
||||||
|
### Tasks
|
||||||
|
- `GET /tasks/` - List all tasks (with filtering options)
|
||||||
|
- `POST /tasks/` - Create a new task
|
||||||
|
- `GET /tasks/{task_id}` - Get a specific task
|
||||||
|
- `PUT /tasks/{task_id}` - Update a task
|
||||||
|
- `DELETE /tasks/{task_id}` - Delete a task
|
||||||
|
|
||||||
|
### Categories
|
||||||
|
- `GET /categories/` - List all categories
|
||||||
|
- `POST /categories/` - Create a new category
|
||||||
|
- `GET /categories/{category_id}` - Get a specific category
|
||||||
|
- `PUT /categories/{category_id}` - Update a category
|
||||||
|
- `DELETE /categories/{category_id}` - Delete a category
|
||||||
|
|
||||||
|
### System
|
||||||
|
- `GET /` - API information and links
|
||||||
|
- `GET /health` - Health check endpoint
|
||||||
|
|
||||||
|
## Data Models
|
||||||
|
|
||||||
|
### Task
|
||||||
|
- `id`: Unique identifier
|
||||||
|
- `title`: Task title (required)
|
||||||
|
- `description`: Optional task description
|
||||||
|
- `status`: pending, in_progress, completed, cancelled
|
||||||
|
- `priority`: low, medium, high, urgent
|
||||||
|
- `due_date`: Optional due date
|
||||||
|
- `category_id`: Optional category association
|
||||||
|
- `completed_at`: Timestamp when task was completed
|
||||||
|
- `created_at/updated_at`: Timestamps
|
||||||
|
|
||||||
|
### Category
|
||||||
|
- `id`: Unique identifier
|
||||||
|
- `name`: Category name (required)
|
||||||
|
- `description`: Optional description
|
||||||
|
- `color`: Optional color code
|
||||||
|
- `created_at/updated_at`: Timestamps
|
||||||
|
|
||||||
|
### User
|
||||||
|
- `id`: Unique identifier
|
||||||
|
- `email`: User email (unique, required)
|
||||||
|
- `full_name`: Optional full name
|
||||||
|
- `is_active`: Account status
|
||||||
|
- `created_at/updated_at`: Timestamps
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
Set the following environment variables for production:
|
||||||
|
|
||||||
|
- `SECRET_KEY`: JWT secret key for token signing (required for production)
|
||||||
|
|
||||||
|
Example:
|
||||||
|
```bash
|
||||||
|
export SECRET_KEY="your-super-secret-key-here"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
The application uses SQLite by default with the database file stored at `/app/storage/db/db.sqlite`. The database is automatically created when the application starts.
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
|
||||||
|
The API uses JWT bearer tokens for authentication. To access protected endpoints:
|
||||||
|
|
||||||
|
1. Register a new user or login with existing credentials
|
||||||
|
2. Include the access token in the Authorization header: `Authorization: Bearer <token>`
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
### Code Quality
|
||||||
|
|
||||||
|
The project uses Ruff for linting and code formatting:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ruff check .
|
||||||
|
ruff format .
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database Migrations
|
||||||
|
|
||||||
|
Create new migrations after model changes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
alembic revision --autogenerate -m "Description of changes"
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
- **FastAPI**: Modern, fast web framework for building APIs
|
||||||
|
- **SQLAlchemy**: ORM for database operations
|
||||||
|
- **Alembic**: Database migration tool
|
||||||
|
- **Pydantic**: Data validation using Python type annotations
|
||||||
|
- **JWT**: JSON Web Tokens for authentication
|
||||||
|
- **SQLite**: Lightweight database for development and small deployments
|
||||||
|
|
||||||
|
The application follows a clean architecture pattern with separate layers for:
|
||||||
|
- API routes (`app/api/`)
|
||||||
|
- Database models (`app/models/`)
|
||||||
|
- Data schemas (`app/schemas/`)
|
||||||
|
- Core utilities (`app/core/`)
|
||||||
|
- Database configuration (`app/db/`)
|
||||||
|
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
|
51
alembic/env.py
Normal file
51
alembic/env.py
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
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.insert(0, os.path.dirname(os.path.dirname(__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"}
|
77
alembic/versions/001_initial_migration.py
Normal file
77
alembic/versions/001_initial_migration.py
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
"""Initial migration
|
||||||
|
|
||||||
|
Revision ID: 001
|
||||||
|
Revises:
|
||||||
|
Create Date: 2024-12-20 12: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:
|
||||||
|
# Create users table
|
||||||
|
op.create_table('users',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('email', sa.String(), nullable=False),
|
||||||
|
sa.Column('hashed_password', sa.String(), nullable=False),
|
||||||
|
sa.Column('full_name', sa.String(), nullable=True),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
|
||||||
|
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
|
||||||
|
|
||||||
|
# Create categories table
|
||||||
|
op.create_table('categories',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('description', sa.String(), nullable=True),
|
||||||
|
sa.Column('color', sa.String(), nullable=True),
|
||||||
|
sa.Column('owner_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_categories_id'), 'categories', ['id'], unique=False)
|
||||||
|
|
||||||
|
# Create tasks table
|
||||||
|
op.create_table('tasks',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('title', sa.String(), nullable=False),
|
||||||
|
sa.Column('description', sa.Text(), nullable=True),
|
||||||
|
sa.Column('status', sa.Enum('PENDING', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED', name='taskstatus'), nullable=True),
|
||||||
|
sa.Column('priority', sa.Enum('LOW', 'MEDIUM', 'HIGH', 'URGENT', name='taskpriority'), nullable=True),
|
||||||
|
sa.Column('due_date', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column('completed_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column('owner_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('category_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ),
|
||||||
|
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),
|
||||||
|
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')
|
||||||
|
op.drop_index(op.f('ix_categories_id'), table_name='categories')
|
||||||
|
op.drop_table('categories')
|
||||||
|
op.drop_index(op.f('ix_users_id'), table_name='users')
|
||||||
|
op.drop_index(op.f('ix_users_email'), table_name='users')
|
||||||
|
op.drop_table('users')
|
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# App package
|
1
app/api/__init__.py
Normal file
1
app/api/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# API modules
|
60
app/api/auth.py
Normal file
60
app/api/auth.py
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from fastapi.security import HTTPBearer
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.db.session import get_db
|
||||||
|
from app.core.security import verify_password, get_password_hash, create_access_token
|
||||||
|
from app.core.deps import get_current_active_user
|
||||||
|
from app.models.user import User as UserModel
|
||||||
|
from app.schemas.user import User, UserCreate, Token
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
security = HTTPBearer()
|
||||||
|
|
||||||
|
@router.post("/register", response_model=User)
|
||||||
|
def register(
|
||||||
|
user: UserCreate,
|
||||||
|
db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
# Check if user already exists
|
||||||
|
db_user = db.query(UserModel).filter(UserModel.email == user.email).first()
|
||||||
|
if db_user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Email already registered"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create new user
|
||||||
|
hashed_password = get_password_hash(user.password)
|
||||||
|
db_user = UserModel(
|
||||||
|
email=user.email,
|
||||||
|
hashed_password=hashed_password,
|
||||||
|
full_name=user.full_name,
|
||||||
|
is_active=user.is_active
|
||||||
|
)
|
||||||
|
db.add(db_user)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_user)
|
||||||
|
return db_user
|
||||||
|
|
||||||
|
@router.post("/login", response_model=Token)
|
||||||
|
def login(
|
||||||
|
email: str,
|
||||||
|
password: str,
|
||||||
|
db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
user = db.query(UserModel).filter(UserModel.email == email).first()
|
||||||
|
if not user or not verify_password(password, user.hashed_password):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Incorrect email or password",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
if not user.is_active:
|
||||||
|
raise HTTPException(status_code=400, detail="Inactive user")
|
||||||
|
|
||||||
|
access_token = create_access_token(subject=user.id)
|
||||||
|
return {"access_token": access_token, "token_type": "bearer"}
|
||||||
|
|
||||||
|
@router.get("/me", response_model=User)
|
||||||
|
def read_users_me(current_user: UserModel = Depends(get_current_active_user)):
|
||||||
|
return current_user
|
87
app/api/categories.py
Normal file
87
app/api/categories.py
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
from typing import List
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.db.session import get_db
|
||||||
|
from app.core.deps import get_current_active_user
|
||||||
|
from app.models.user import User
|
||||||
|
from app.models.category import Category as CategoryModel
|
||||||
|
from app.schemas.category import Category, CategoryCreate, CategoryUpdate
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post("/", response_model=Category)
|
||||||
|
def create_category(
|
||||||
|
category: CategoryCreate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_active_user)
|
||||||
|
):
|
||||||
|
db_category = CategoryModel(**category.dict(), owner_id=current_user.id)
|
||||||
|
db.add(db_category)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_category)
|
||||||
|
return db_category
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[Category])
|
||||||
|
def read_categories(
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_active_user)
|
||||||
|
):
|
||||||
|
categories = db.query(CategoryModel).filter(
|
||||||
|
CategoryModel.owner_id == current_user.id
|
||||||
|
).offset(skip).limit(limit).all()
|
||||||
|
return categories
|
||||||
|
|
||||||
|
@router.get("/{category_id}", response_model=Category)
|
||||||
|
def read_category(
|
||||||
|
category_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_active_user)
|
||||||
|
):
|
||||||
|
category = db.query(CategoryModel).filter(
|
||||||
|
CategoryModel.id == category_id,
|
||||||
|
CategoryModel.owner_id == current_user.id
|
||||||
|
).first()
|
||||||
|
if category is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Category not found")
|
||||||
|
return category
|
||||||
|
|
||||||
|
@router.put("/{category_id}", response_model=Category)
|
||||||
|
def update_category(
|
||||||
|
category_id: int,
|
||||||
|
category_update: CategoryUpdate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_active_user)
|
||||||
|
):
|
||||||
|
category = db.query(CategoryModel).filter(
|
||||||
|
CategoryModel.id == category_id,
|
||||||
|
CategoryModel.owner_id == current_user.id
|
||||||
|
).first()
|
||||||
|
if category is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Category not found")
|
||||||
|
|
||||||
|
update_data = category_update.dict(exclude_unset=True)
|
||||||
|
for field, value in update_data.items():
|
||||||
|
setattr(category, field, value)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(category)
|
||||||
|
return category
|
||||||
|
|
||||||
|
@router.delete("/{category_id}")
|
||||||
|
def delete_category(
|
||||||
|
category_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_active_user)
|
||||||
|
):
|
||||||
|
category = db.query(CategoryModel).filter(
|
||||||
|
CategoryModel.id == category_id,
|
||||||
|
CategoryModel.owner_id == current_user.id
|
||||||
|
).first()
|
||||||
|
if category is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Category not found")
|
||||||
|
|
||||||
|
db.delete(category)
|
||||||
|
db.commit()
|
||||||
|
return {"message": "Category deleted successfully"}
|
102
app/api/tasks.py
Normal file
102
app/api/tasks.py
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
from typing import List, Optional
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from datetime import datetime
|
||||||
|
from app.db.session import get_db
|
||||||
|
from app.core.deps import get_current_active_user
|
||||||
|
from app.models.user import User
|
||||||
|
from app.models.task import Task as TaskModel, TaskStatus
|
||||||
|
from app.schemas.task import Task, TaskCreate, TaskUpdate
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post("/", response_model=Task)
|
||||||
|
def create_task(
|
||||||
|
task: TaskCreate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_active_user)
|
||||||
|
):
|
||||||
|
db_task = TaskModel(**task.dict(), owner_id=current_user.id)
|
||||||
|
db.add(db_task)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_task)
|
||||||
|
return db_task
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[Task])
|
||||||
|
def read_tasks(
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
status: Optional[TaskStatus] = Query(None),
|
||||||
|
category_id: Optional[int] = Query(None),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_active_user)
|
||||||
|
):
|
||||||
|
query = db.query(TaskModel).filter(TaskModel.owner_id == current_user.id)
|
||||||
|
|
||||||
|
if status:
|
||||||
|
query = query.filter(TaskModel.status == status)
|
||||||
|
if category_id:
|
||||||
|
query = query.filter(TaskModel.category_id == category_id)
|
||||||
|
|
||||||
|
tasks = query.offset(skip).limit(limit).all()
|
||||||
|
return tasks
|
||||||
|
|
||||||
|
@router.get("/{task_id}", response_model=Task)
|
||||||
|
def read_task(
|
||||||
|
task_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_active_user)
|
||||||
|
):
|
||||||
|
task = db.query(TaskModel).filter(
|
||||||
|
TaskModel.id == task_id,
|
||||||
|
TaskModel.owner_id == current_user.id
|
||||||
|
).first()
|
||||||
|
if task is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Task not found")
|
||||||
|
return task
|
||||||
|
|
||||||
|
@router.put("/{task_id}", response_model=Task)
|
||||||
|
def update_task(
|
||||||
|
task_id: int,
|
||||||
|
task_update: TaskUpdate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_active_user)
|
||||||
|
):
|
||||||
|
task = db.query(TaskModel).filter(
|
||||||
|
TaskModel.id == task_id,
|
||||||
|
TaskModel.owner_id == current_user.id
|
||||||
|
).first()
|
||||||
|
if task is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Task not found")
|
||||||
|
|
||||||
|
update_data = task_update.dict(exclude_unset=True)
|
||||||
|
|
||||||
|
# Set completed_at when task is marked as completed
|
||||||
|
if update_data.get("status") == TaskStatus.COMPLETED and task.status != TaskStatus.COMPLETED:
|
||||||
|
update_data["completed_at"] = datetime.utcnow()
|
||||||
|
elif update_data.get("status") != TaskStatus.COMPLETED:
|
||||||
|
update_data["completed_at"] = None
|
||||||
|
|
||||||
|
for field, value in update_data.items():
|
||||||
|
setattr(task, field, value)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(task)
|
||||||
|
return task
|
||||||
|
|
||||||
|
@router.delete("/{task_id}")
|
||||||
|
def delete_task(
|
||||||
|
task_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_active_user)
|
||||||
|
):
|
||||||
|
task = db.query(TaskModel).filter(
|
||||||
|
TaskModel.id == task_id,
|
||||||
|
TaskModel.owner_id == current_user.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"}
|
1
app/core/__init__.py
Normal file
1
app/core/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Core modules
|
39
app/core/deps.py
Normal file
39
app/core/deps.py
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||||
|
from jose import jwt, JWTError
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.db.session import get_db
|
||||||
|
from app.core.security import SECRET_KEY, ALGORITHM
|
||||||
|
from app.models.user import User
|
||||||
|
|
||||||
|
security = HTTPBearer()
|
||||||
|
|
||||||
|
def get_current_user(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
credentials: HTTPAuthorizationCredentials = Depends(security)
|
||||||
|
) -> User:
|
||||||
|
credentials_exception = HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Could not validate credentials",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
|
||||||
|
user_id: str = payload.get("sub")
|
||||||
|
if user_id is None:
|
||||||
|
raise credentials_exception
|
||||||
|
except JWTError:
|
||||||
|
raise credentials_exception
|
||||||
|
|
||||||
|
user = db.query(User).filter(User.id == int(user_id)).first()
|
||||||
|
if user is None:
|
||||||
|
raise credentials_exception
|
||||||
|
return user
|
||||||
|
|
||||||
|
def get_current_active_user(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
) -> User:
|
||||||
|
if not current_user.is_active:
|
||||||
|
raise HTTPException(status_code=400, detail="Inactive user")
|
||||||
|
return current_user
|
30
app/core/security.py
Normal file
30
app/core/security.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
import os
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any, Union
|
||||||
|
from jose import jwt
|
||||||
|
from passlib.context import CryptContext
|
||||||
|
|
||||||
|
SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key-change-in-production")
|
||||||
|
ALGORITHM = "HS256"
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
||||||
|
|
||||||
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
|
def create_access_token(
|
||||||
|
subject: Union[str, Any], expires_delta: timedelta = None
|
||||||
|
) -> str:
|
||||||
|
if expires_delta:
|
||||||
|
expire = datetime.utcnow() + expires_delta
|
||||||
|
else:
|
||||||
|
expire = datetime.utcnow() + timedelta(
|
||||||
|
minutes=ACCESS_TOKEN_EXPIRE_MINUTES
|
||||||
|
)
|
||||||
|
to_encode = {"exp": expire, "sub": str(subject)}
|
||||||
|
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||||
|
return encoded_jwt
|
||||||
|
|
||||||
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||||
|
return pwd_context.verify(plain_password, hashed_password)
|
||||||
|
|
||||||
|
def get_password_hash(password: str) -> str:
|
||||||
|
return pwd_context.hash(password)
|
1
app/db/__init__.py
Normal file
1
app/db/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Database modules
|
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()
|
26
app/db/session.py
Normal file
26
app/db/session.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
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)
|
5
app/models/__init__.py
Normal file
5
app/models/__init__.py
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
from .user import User
|
||||||
|
from .task import Task, TaskStatus, TaskPriority
|
||||||
|
from .category import Category
|
||||||
|
|
||||||
|
__all__ = ["User", "Task", "TaskStatus", "TaskPriority", "Category"]
|
18
app/models/category.py
Normal file
18
app/models/category.py
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
class Category(Base):
|
||||||
|
__tablename__ = "categories"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
description = Column(String, nullable=True)
|
||||||
|
color = Column(String, nullable=True)
|
||||||
|
owner_id = Column(Integer, ForeignKey("users.id"))
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||||
|
|
||||||
|
owner = relationship("User", back_populates="categories")
|
||||||
|
tasks = relationship("Task", back_populates="category")
|
35
app/models/task.py
Normal file
35
app/models/task.py
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Enum
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from enum import Enum as PyEnum
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
class TaskStatus(PyEnum):
|
||||||
|
PENDING = "pending"
|
||||||
|
IN_PROGRESS = "in_progress"
|
||||||
|
COMPLETED = "completed"
|
||||||
|
CANCELLED = "cancelled"
|
||||||
|
|
||||||
|
class TaskPriority(PyEnum):
|
||||||
|
LOW = "low"
|
||||||
|
MEDIUM = "medium"
|
||||||
|
HIGH = "high"
|
||||||
|
URGENT = "urgent"
|
||||||
|
|
||||||
|
class Task(Base):
|
||||||
|
__tablename__ = "tasks"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
title = Column(String, nullable=False, index=True)
|
||||||
|
description = Column(Text, nullable=True)
|
||||||
|
status = Column(Enum(TaskStatus), default=TaskStatus.PENDING)
|
||||||
|
priority = Column(Enum(TaskPriority), default=TaskPriority.MEDIUM)
|
||||||
|
due_date = Column(DateTime(timezone=True), nullable=True)
|
||||||
|
completed_at = Column(DateTime(timezone=True), nullable=True)
|
||||||
|
owner_id = Column(Integer, ForeignKey("users.id"))
|
||||||
|
category_id = Column(Integer, ForeignKey("categories.id"), nullable=True)
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||||
|
|
||||||
|
owner = relationship("User", back_populates="tasks")
|
||||||
|
category = relationship("Category", back_populates="tasks")
|
18
app/models/user.py
Normal file
18
app/models/user.py
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, DateTime, Boolean
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
__tablename__ = "users"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
email = Column(String, unique=True, index=True, nullable=False)
|
||||||
|
hashed_password = Column(String, nullable=False)
|
||||||
|
full_name = Column(String, nullable=True)
|
||||||
|
is_active = Column(Boolean, default=True)
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||||
|
|
||||||
|
tasks = relationship("Task", back_populates="owner")
|
||||||
|
categories = relationship("Category", back_populates="owner")
|
9
app/schemas/__init__.py
Normal file
9
app/schemas/__init__.py
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
from .user import User, UserCreate, UserUpdate, Token
|
||||||
|
from .task import Task, TaskCreate, TaskUpdate
|
||||||
|
from .category import Category, CategoryCreate, CategoryUpdate
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"User", "UserCreate", "UserUpdate", "Token",
|
||||||
|
"Task", "TaskCreate", "TaskUpdate",
|
||||||
|
"Category", "CategoryCreate", "CategoryUpdate"
|
||||||
|
]
|
28
app/schemas/category.py
Normal file
28
app/schemas/category.py
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
class CategoryBase(BaseModel):
|
||||||
|
name: str
|
||||||
|
description: Optional[str] = None
|
||||||
|
color: Optional[str] = None
|
||||||
|
|
||||||
|
class CategoryCreate(CategoryBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class CategoryUpdate(BaseModel):
|
||||||
|
name: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
color: Optional[str] = None
|
||||||
|
|
||||||
|
class CategoryInDBBase(CategoryBase):
|
||||||
|
id: int
|
||||||
|
owner_id: int
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
class Category(CategoryInDBBase):
|
||||||
|
pass
|
36
app/schemas/task.py
Normal file
36
app/schemas/task.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from datetime import datetime
|
||||||
|
from app.models.task import TaskStatus, TaskPriority
|
||||||
|
|
||||||
|
class TaskBase(BaseModel):
|
||||||
|
title: str
|
||||||
|
description: Optional[str] = None
|
||||||
|
status: TaskStatus = TaskStatus.PENDING
|
||||||
|
priority: TaskPriority = TaskPriority.MEDIUM
|
||||||
|
due_date: Optional[datetime] = None
|
||||||
|
category_id: Optional[int] = None
|
||||||
|
|
||||||
|
class TaskCreate(TaskBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class TaskUpdate(BaseModel):
|
||||||
|
title: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
status: Optional[TaskStatus] = None
|
||||||
|
priority: Optional[TaskPriority] = None
|
||||||
|
due_date: Optional[datetime] = None
|
||||||
|
category_id: Optional[int] = None
|
||||||
|
|
||||||
|
class TaskInDBBase(TaskBase):
|
||||||
|
id: int
|
||||||
|
owner_id: int
|
||||||
|
completed_at: Optional[datetime] = None
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
class Task(TaskInDBBase):
|
||||||
|
pass
|
38
app/schemas/user.py
Normal file
38
app/schemas/user.py
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel, EmailStr
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
class UserBase(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
full_name: Optional[str] = None
|
||||||
|
is_active: bool = True
|
||||||
|
|
||||||
|
class UserCreate(UserBase):
|
||||||
|
password: str
|
||||||
|
|
||||||
|
class UserUpdate(BaseModel):
|
||||||
|
email: Optional[EmailStr] = None
|
||||||
|
full_name: Optional[str] = None
|
||||||
|
is_active: Optional[bool] = None
|
||||||
|
password: Optional[str] = None
|
||||||
|
|
||||||
|
class UserInDBBase(UserBase):
|
||||||
|
id: int
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
class User(UserInDBBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class UserInDB(UserInDBBase):
|
||||||
|
hashed_password: str
|
||||||
|
|
||||||
|
class Token(BaseModel):
|
||||||
|
access_token: str
|
||||||
|
token_type: str
|
||||||
|
|
||||||
|
class TokenData(BaseModel):
|
||||||
|
user_id: Optional[int] = None
|
46
main.py
Normal file
46
main.py
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from app.api import auth, tasks, categories
|
||||||
|
from app.db.session import create_tables
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="Personal Task Management API",
|
||||||
|
description="A comprehensive API for managing personal tasks, categories, and user authentication",
|
||||||
|
version="1.0.0",
|
||||||
|
openapi_url="/openapi.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
# CORS middleware
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create database tables
|
||||||
|
create_tables()
|
||||||
|
|
||||||
|
# Include routers
|
||||||
|
app.include_router(auth.router, prefix="/auth", tags=["authentication"])
|
||||||
|
app.include_router(tasks.router, prefix="/tasks", tags=["tasks"])
|
||||||
|
app.include_router(categories.router, prefix="/categories", tags=["categories"])
|
||||||
|
|
||||||
|
@app.get("/")
|
||||||
|
def read_root():
|
||||||
|
return {
|
||||||
|
"title": "Personal Task Management API",
|
||||||
|
"description": "A comprehensive API for managing personal tasks and categories",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"documentation": "/docs",
|
||||||
|
"health_check": "/health"
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health_check():
|
||||||
|
return {
|
||||||
|
"status": "healthy",
|
||||||
|
"service": "Personal Task Management API",
|
||||||
|
"version": "1.0.0"
|
||||||
|
}
|
10
requirements.txt
Normal file
10
requirements.txt
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
fastapi==0.104.1
|
||||||
|
uvicorn[standard]==0.24.0
|
||||||
|
sqlalchemy==2.0.23
|
||||||
|
alembic==1.13.1
|
||||||
|
pydantic==2.5.0
|
||||||
|
python-multipart==0.0.6
|
||||||
|
python-jose[cryptography]==3.3.0
|
||||||
|
passlib[bcrypt]==1.7.4
|
||||||
|
python-decouple==3.8
|
||||||
|
ruff==0.1.6
|
Loading…
x
Reference in New Issue
Block a user