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.
- Features
- Technology Stack
- Project Structure
- API Endpoints
- Installation
- Usage Examples
- Testing
- Database
- Authentication
- Docker Deployment
- Environment Variables
- API Documentation
- 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
- 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
- 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
- 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
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
- POST
/auth/register - Purpose: Create a new user account
- Body:
{"username": "string", "email": "string", "password": "string"} - Response: User details (excluding password)
- POST
/auth/token - Purpose: Authenticate user and receive access token
- Body: Form data with
usernameandpassword - Response:
{"access_token": "string", "token_type": "bearer"}
- GET
/auth/me - Purpose: Retrieve current authenticated user information
- Headers:
Authorization: Bearer <token> - Response: Current user details
- POST
/tasks/ - Purpose: Create a new task for the authenticated user
- Headers:
Authorization: Bearer <token> - Body:
{"title": "string", "description": "string"} - Response: Created task details
- 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
/tasks/{task_id} - Purpose: Retrieve a specific task by ID
- Headers:
Authorization: Bearer <token> - Response: Task details or 404 if not found/not owned
- 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
/tasks/{task_id} - Purpose: Permanently delete a task
- Headers:
Authorization: Bearer <token> - Response: Success message or 404 if not found
- GET
/health - Purpose: Check API status
- Response:
{"status": "healthy"}
- GET
/ - Purpose: API welcome message
- Response:
{"message": "Welcome to Todo List API"}
- Python 3.11 or higher
- pip (Python package installer)
- Git
- Clone the repository
git clone <repository-url>
cd "API RESTful"- Create virtual environment
python -m venv .venv- Activate virtual environment
# Windows
.venv\Scripts\activate
# Linux/Mac
source .venv/bin/activate- Install dependencies
pip install -r requirements.txt- Configure environment variables
cp .env.example .env
# Edit .env file with your configuration- Run the application
uvicorn app.main:app --reloadThe API will be available at http://localhost:8000
curl -X POST "http://localhost:8000/auth/register" \
-H "Content-Type: application/json" \
-d '{
"username": "john_doe",
"email": "john@example.com",
"password": "secure_password123"
}'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"
}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"
}'curl -X GET "http://localhost:8000/tasks/" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"curl -X PUT "http://localhost:8000/tasks/1" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"completed": true}'curl -X DELETE "http://localhost:8000/tasks/1" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"pytestpytest --cov=app# Test authentication endpoints
pytest tests/test_auth.py
# Test task management endpoints
pytest tests/test_tasks.py- 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
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)
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)
- 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
- 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
- User registers with username, email, and password
- Password is hashed using bcrypt before storage
- User logs in with username and password
- Server verifies credentials and generates JWT token
- Client includes token in Authorization header for protected requests
- Server validates token and extracts user information
- User data is retrieved from database for request processing
# Start the application with PostgreSQL database
docker-compose up --build
# Run in background
docker-compose up -d --build
# Stop the application
docker-compose down# Build the image
docker build -t todo-api .
# Run the container
docker run -p 8000:8000 -e DATABASE_URL="sqlite:///./todo.db" todo-api- PostgreSQL database container
- Environment-specific configurations
- Volume mounting for data persistence
- Network configuration for service communication
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- 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
- Swagger UI: Available at
http://localhost:8000/docs - ReDoc: Available at
http://localhost:8000/redoc - OpenAPI Specification: Available at
http://localhost:8000/openapi.json
- Navigate to
http://localhost:8000/docs - Click on any endpoint to expand its details
- Click "Try it out" to test the endpoint
- For protected endpoints, click the lock icon and enter your JWT token
- Fill in the required parameters and click "Execute"
- View the response in the interface
A simple HTML interface is provided in frontend-test/index.html for testing the API:
- Start the API server
- Open
frontend-test/index.htmlin a web browser - Use the interface to register, login, and manage tasks
- 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
- 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
This project is licensed under the MIT License - see the LICENSE file for details.