Skip to content

gustavohenrip/API-RESTful-Todo-List

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Todo List API

A RESTful API for task management with user authentication, built with FastAPI. This project demonstrates modern backend development practices including JWT authentication, CRUD operations, automated testing, API documentation, and containerization.

Development Assistant: This project was developed with assistance from Claude Sonnet 4 AI.

Table of Contents

Features

Core Functionality

  • User Management: Complete user registration and authentication system
  • Task Management: Full CRUD operations for tasks (Create, Read, Update, Delete)
  • User Isolation: Each user can only access their own tasks
  • Data Persistence: All data is stored in a relational database

Security Features

  • JWT Authentication: Secure token-based authentication
  • Password Hashing: Passwords are securely hashed using bcrypt
  • Protected Routes: Task operations require valid authentication
  • CORS Support: Cross-Origin Resource Sharing configured for frontend integration

Development Features

  • Automatic Documentation: Interactive API documentation with Swagger UI
  • Automated Testing: Comprehensive test suite with pytest
  • Containerization: Docker support for easy deployment
  • Hot Reload: Development server with automatic code reloading
  • Environment Configuration: Secure configuration management with environment variables

Technology Stack

  • Framework: FastAPI - Modern, fast web framework for building APIs
  • Database: SQLite (development) / PostgreSQL (production)
  • ORM: SQLAlchemy - Python SQL toolkit and Object-Relational Mapping
  • Authentication: JWT (JSON Web Tokens) with python-jose
  • Password Security: Passlib with bcrypt hashing
  • Testing: Pytest with test client for API testing
  • Documentation: Automatic OpenAPI/Swagger documentation
  • Containerization: Docker and Docker Compose
  • Configuration: Python-decouple for environment variable management

Project Structure

app/
├── __init__.py
├── main.py              # Application entry point and FastAPI configuration
├── database.py          # Database connection and session management
├── models.py            # SQLAlchemy database models (User, Task)
├── schemas.py           # Pydantic schemas for request/response validation
├── auth.py              # JWT authentication utilities
├── services.py          # Business logic and database operations
└── routers/
    ├── __init__.py
    ├── auth.py          # Authentication endpoints (register, login)
    └── tasks.py         # Task management endpoints (CRUD operations)
tests/
├── __init__.py
├── conftest.py          # Test configuration and fixtures
├── test_auth.py         # Authentication endpoint tests
└── test_tasks.py        # Task management endpoint tests
frontend-test/
└── index.html           # Simple HTML interface for testing the API

API Endpoints

Authentication Endpoints

Register User

  • POST /auth/register
  • Purpose: Create a new user account
  • Body: {"username": "string", "email": "string", "password": "string"}
  • Response: User details (excluding password)

Login

  • POST /auth/token
  • Purpose: Authenticate user and receive access token
  • Body: Form data with username and password
  • Response: {"access_token": "string", "token_type": "bearer"}

Get Current User

  • GET /auth/me
  • Purpose: Retrieve current authenticated user information
  • Headers: Authorization: Bearer <token>
  • Response: Current user details

Task Management Endpoints

Create Task

  • POST /tasks/
  • Purpose: Create a new task for the authenticated user
  • Headers: Authorization: Bearer <token>
  • Body: {"title": "string", "description": "string"}
  • Response: Created task details

List Tasks

  • GET /tasks/
  • Purpose: Retrieve all tasks belonging to the authenticated user
  • Headers: Authorization: Bearer <token>
  • Query Parameters: skip (offset), limit (max results)
  • Response: Array of user's tasks

Get Specific Task

  • GET /tasks/{task_id}
  • Purpose: Retrieve a specific task by ID
  • Headers: Authorization: Bearer <token>
  • Response: Task details or 404 if not found/not owned

Update Task

  • PUT /tasks/{task_id}
  • Purpose: Update task details or completion status
  • Headers: Authorization: Bearer <token>
  • Body: {"title": "string", "description": "string", "completed": boolean}
  • Response: Updated task details

Delete Task

  • DELETE /tasks/{task_id}
  • Purpose: Permanently delete a task
  • Headers: Authorization: Bearer <token>
  • Response: Success message or 404 if not found

System Endpoints

Health Check

  • GET /health
  • Purpose: Check API status
  • Response: {"status": "healthy"}

Root

  • GET /
  • Purpose: API welcome message
  • Response: {"message": "Welcome to Todo List API"}

Installation

Prerequisites

  • Python 3.11 or higher
  • pip (Python package installer)
  • Git

Local Development Setup

  1. Clone the repository
git clone <repository-url>
cd "API RESTful"
  1. Create virtual environment
python -m venv .venv
  1. Activate virtual environment
# Windows
.venv\Scripts\activate
# Linux/Mac
source .venv/bin/activate
  1. Install dependencies
pip install -r requirements.txt
  1. Configure environment variables
cp .env.example .env
# Edit .env file with your configuration
  1. Run the application
uvicorn app.main:app --reload

The API will be available at http://localhost:8000

Usage Examples

1. Register a New User

curl -X POST "http://localhost:8000/auth/register" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john_doe",
    "email": "john@example.com",
    "password": "secure_password123"
  }'

2. Login to Get Access Token

curl -X POST "http://localhost:8000/auth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=john_doe&password=secure_password123"

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer"
}

3. Create a Task

curl -X POST "http://localhost:8000/tasks/" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Complete project documentation",
    "description": "Write comprehensive README and API documentation"
  }'

4. List All Tasks

curl -X GET "http://localhost:8000/tasks/" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

5. Update Task Status

curl -X PUT "http://localhost:8000/tasks/1" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"completed": true}'

6. Delete a Task

curl -X DELETE "http://localhost:8000/tasks/1" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Testing

Run All Tests

pytest

Run Tests with Coverage

pytest --cov=app

Run Specific Test Files

# Test authentication endpoints
pytest tests/test_auth.py

# Test task management endpoints
pytest tests/test_tasks.py

Test Structure

  • Unit Tests: Test individual functions and methods
  • Integration Tests: Test complete API workflows
  • Authentication Tests: Verify JWT token handling
  • CRUD Tests: Verify all database operations

Database

Database Models

User Model

  • id: Primary key (integer)
  • username: Unique username (string)
  • email: Unique email address (string)
  • hashed_password: Bcrypt hashed password (string)
  • is_active: Account status (boolean)
  • created_at: Account creation timestamp (datetime)

Task Model

  • id: Primary key (integer)
  • title: Task title (string)
  • description: Task description (string, optional)
  • completed: Completion status (boolean, default: false)
  • created_at: Task creation timestamp (datetime)
  • updated_at: Last modification timestamp (datetime)
  • owner_id: Foreign key to User (integer)

Database Operations

  • Automatic Migration: Database tables are created automatically on startup
  • Data Isolation: Users can only access their own tasks
  • Referential Integrity: Tasks are linked to users via foreign key
  • SQLite for Development: File-based database for easy development
  • PostgreSQL for Production: Scalable database for production deployment

Authentication

JWT Token System

  • Stateless Authentication: No server-side session storage required
  • Token Expiration: Configurable token lifetime (default: 30 minutes)
  • Secure Algorithm: HS256 algorithm for token signing
  • Password Security: Bcrypt hashing with salt

Authentication Flow

  1. User registers with username, email, and password
  2. Password is hashed using bcrypt before storage
  3. User logs in with username and password
  4. Server verifies credentials and generates JWT token
  5. Client includes token in Authorization header for protected requests
  6. Server validates token and extracts user information
  7. User data is retrieved from database for request processing

Docker Deployment

Using Docker Compose (Recommended)

# Start the application with PostgreSQL database
docker-compose up --build

# Run in background
docker-compose up -d --build

# Stop the application
docker-compose down

Using Docker Only

# Build the image
docker build -t todo-api .

# Run the container
docker run -p 8000:8000 -e DATABASE_URL="sqlite:///./todo.db" todo-api

Production Configuration

  • PostgreSQL database container
  • Environment-specific configurations
  • Volume mounting for data persistence
  • Network configuration for service communication

Environment Variables

Create a .env file in the project root:

# Database Configuration
DATABASE_URL=sqlite:///./tododb.db
# For PostgreSQL: postgresql://username:password@localhost:5432/database_name

# JWT Configuration
SECRET_KEY=your-super-secret-key-change-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

Variable Descriptions

  • DATABASE_URL: Database connection string
  • SECRET_KEY: Secret key for JWT token signing (must be changed in production)
  • ALGORITHM: JWT signing algorithm
  • ACCESS_TOKEN_EXPIRE_MINUTES: Token expiration time in minutes

API Documentation

Interactive Documentation

  • Swagger UI: Available at http://localhost:8000/docs
  • ReDoc: Available at http://localhost:8000/redoc
  • OpenAPI Specification: Available at http://localhost:8000/openapi.json

Using Swagger UI

  1. Navigate to http://localhost:8000/docs
  2. Click on any endpoint to expand its details
  3. Click "Try it out" to test the endpoint
  4. For protected endpoints, click the lock icon and enter your JWT token
  5. Fill in the required parameters and click "Execute"
  6. View the response in the interface

Frontend Test Interface

A simple HTML interface is provided in frontend-test/index.html for testing the API:

  1. Start the API server
  2. Open frontend-test/index.html in a web browser
  3. Use the interface to register, login, and manage tasks

Security Considerations

Development vs Production

  • Development: Uses SQLite database with simple configuration
  • Production: Should use PostgreSQL with secure environment variables
  • Secret Key: Must be changed from default value in production
  • HTTPS: Should be used in production for secure token transmission
  • CORS: Configure allowed origins appropriately for production

Best Practices Implemented

  • Password hashing with bcrypt
  • JWT token expiration
  • Input validation with Pydantic schemas
  • SQL injection prevention through ORM
  • Environment variable configuration
  • Automated testing for security-critical functions

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

A robust RESTful API for task management with user authentication, built using FastAPI. Features include JWT authentication, CRUD operations for tasks, automated tests, Docker support, environment variable configuration, and clear code structure. Designed for scalability and production use.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors