Skip to content

fahmikudo/web_rust

Repository files navigation

Todo List API - Rust & Actix Web

A comprehensive To-Do List REST API built with Rust, Actix Web, and MySQL featuring authentication, authorization, and middleware.

Features

  • RESTful API for Todo management
  • MySQL Database with SQLX for data persistence
  • JWT Authentication & Authorization
  • Environment Variables with .env support
  • Middleware for error handling and logging
  • Clean Architecture with proper separation of concerns
  • Input Validation using validator crate
  • Password Hashing with bcrypt
  • CORS Support for frontend integration
  • Database Migrations with SQLX

Architecture

The project follows a clean architecture pattern:

src/
├── config/         # Configuration management
├── models/         # Database models
├── dto/           # Data Transfer Objects
├── repositories/  # Database access layer
├── services/      # Business logic layer
├── handlers/      # HTTP request handlers
├── middleware/    # Custom middleware
└── utils/         # Utility functions

Prerequisites

  • Rust 1.70+
  • MySQL 8.0+
  • Cargo

Environment Setup

  1. Copy the example environment file:
cp .env.example .env
  1. Update the .env file with your database credentials:
DATABASE_URL=mysql://username:password@localhost:3306/todo_db
SERVER_HOST=127.0.0.1
SERVER_PORT=8080
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRATION=24h
RUST_LOG=debug
ENVIRONMENT=development
  1. Create a MySQL database:
CREATE DATABASE todo_db;

Installation & Running

  1. Clone the repository
  2. Install dependencies:
cargo build
  1. Run the application:
cargo run

The server will start on http://127.0.0.1:8080

API Endpoints

Authentication

  • POST /api/v1/auth/register - Register a new user
  • POST /api/v1/auth/login - Login user
  • GET /api/v1/auth/me - Get current user (requires auth)

Todos

  • POST /api/v1/todos - Create a new todo (requires auth)
  • GET /api/v1/todos - Get todos with pagination (requires auth)
  • GET /api/v1/todos/{id} - Get specific todo (requires auth)
  • PUT /api/v1/todos/{id} - Update todo (requires auth)
  • DELETE /api/v1/todos/{id} - Delete todo (requires auth)

Health Check

  • GET /health - Server health check

API Usage Examples

Register a new user

curl -X POST http://localhost:8080/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "johndoe",
    "email": "john@example.com",
    "password": "password123"
  }'

Login

curl -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "johndoe",
    "password": "password123"
  }'

Create a todo (with auth token)

curl -X POST http://localhost:8080/api/v1/todos \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "title": "Buy groceries",
    "description": "Milk, eggs, bread",
    "priority": "medium",
    "due_date": "2024-12-31T10:00:00Z"
  }'

Get todos with pagination

curl -X GET "http://localhost:8080/api/v1/todos?page=1&per_page=10" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Project Structure Details

Models

  • User - User entity with authentication data
  • Todo - Todo item with priority levels and timestamps

DTOs

  • Request/Response objects for API endpoints
  • Input validation using the validator crate

Services

  • AuthService - Handles user registration, login, and JWT operations
  • TodoService - Manages todo CRUD operations

Middleware

  • AuthMiddleware - JWT token validation and user extraction
  • LoggingMiddleware - Request/response logging

Error Handling

  • Custom AppError enum for different error types
  • Automatic HTTP status code mapping
  • Structured error responses

Security Features

  • Password hashing with bcrypt
  • JWT token-based authentication
  • Request validation
  • SQL injection protection through SQLX
  • CORS configuration

Database Schema

The application uses two main tables:

Users Table

  • id (UUID, Primary Key)
  • username (Unique)
  • email (Unique)
  • password_hash
  • created_at, updated_at

Todos Table

  • id (UUID, Primary Key)
  • user_id (Foreign Key to users)
  • title
  • description (Optional)
  • completed (Boolean)
  • priority (Enum: low, medium, high)
  • due_date (Optional)
  • created_at, updated_at

Development

Running Tests

cargo test

Check code formatting

cargo fmt

Run linting

cargo clippy

Production Deployment

  1. Set ENVIRONMENT=production in your .env
  2. Use a strong JWT_SECRET
  3. Configure proper database credentials
  4. Set up reverse proxy (nginx/Apache)
  5. Enable SSL/TLS
  6. Configure proper logging levels

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

This project is licensed under the MIT License.

About

Vibe Coding Rust

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors