Skip to content

UNC-GDSC/Rust-REST-Boilerplate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rust REST API Boilerplate

A production-ready REST API built with Rust and Axum, featuring authentication, database integration, comprehensive error handling, and Docker support.

Features

  • Modern Web Framework: Built with Axum for high performance and ergonomic API design
  • Authentication & Authorization: JWT-based authentication with secure password hashing (Argon2)
  • Database Integration: PostgreSQL with SQLx for compile-time checked queries
  • Comprehensive Error Handling: Custom error types with proper HTTP status codes
  • Input Validation: Request validation using the validator crate
  • Structured Logging: Request tracing and logging with tracing and tracing-subscriber
  • CORS Support: Configurable Cross-Origin Resource Sharing
  • Health Checks: Liveness and readiness endpoints for orchestration
  • Configuration Management: Environment-based configuration with TOML files
  • Database Migrations: Automated schema migrations with SQLx
  • Testing: Integration tests for API endpoints
  • Docker Support: Multi-stage Dockerfile and Docker Compose setup
  • Production Ready: Optimized build configuration and security best practices

Project Structure

.
├── config/                 # Configuration files
│   ├── default.toml       # Default configuration
│   └── production.toml    # Production overrides
├── migrations/            # Database migrations
├── src/
│   ├── api/              # API layer
│   │   ├── error.rs     # Error handling
│   │   ├── handlers/    # Request handlers
│   │   └── routes.rs    # Route definitions
│   ├── config/          # Configuration module
│   ├── db/              # Database layer
│   │   └── user_repository.rs
│   ├── middleware/      # Custom middleware
│   ├── models/          # Data models
│   ├── services/        # Business logic
│   ├── lib.rs          # Library root
│   └── main.rs         # Application entry point
├── tests/               # Integration tests
├── Dockerfile          # Multi-stage Docker build
├── docker-compose.yml  # Docker Compose configuration
└── Cargo.toml         # Rust dependencies

Quick Start

Prerequisites

  • Rust 1.75 or later
  • PostgreSQL 14 or later
  • Docker and Docker Compose (optional)

Local Development

  1. Clone the repository
git clone https://github.com/yourusername/rust-rest-api.git
cd rust-rest-api
  1. Set up environment variables
cp .env.example .env
# Edit .env with your configuration
  1. Start PostgreSQL (using Docker)
docker run -d \
  --name postgres \
  -e POSTGRES_USER=postgres \
  -e POSTGRES_PASSWORD=postgres \
  -e POSTGRES_DB=rust_api \
  -p 5432:5432 \
  postgres:16-alpine
  1. Run migrations
cargo install sqlx-cli --no-default-features --features postgres
sqlx migrate run
  1. Run the application
cargo run

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

Using Docker Compose

docker-compose up -d

This will start both the PostgreSQL database and the API service.

API Documentation

Authentication Endpoints

Register User

POST /api/v1/register
Content-Type: application/json

{
  "email": "[email protected]",
  "username": "johndoe",
  "password": "securepassword123"
}

Response:

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "[email protected]",
  "username": "johndoe",
  "created_at": "2024-01-01T12:00:00Z",
  "updated_at": "2024-01-01T12:00:00Z"
}

Login

POST /api/v1/login
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "securepassword123"
}

Response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "[email protected]",
    "username": "johndoe",
    "created_at": "2024-01-01T12:00:00Z",
    "updated_at": "2024-01-01T12:00:00Z"
  }
}

User Endpoints (Protected)

All user endpoints require authentication. Include the JWT token in the Authorization header:

Authorization: Bearer <your-jwt-token>

Get All Users

GET /api/v1/users?page=1&per_page=10

Response:

{
  "data": [...],
  "total": 100,
  "page": 1,
  "per_page": 10,
  "total_pages": 10
}

Get User by ID

GET /api/v1/users/{id}

Get Current User

GET /api/v1/users/me

Update User

PUT /api/v1/users/{id}
Content-Type: application/json

{
  "email": "[email protected]",
  "username": "newusername"
}

Delete User

DELETE /api/v1/users/{id}

Health Check Endpoints

Health Check

GET /health

Readiness Check

GET /ready

Liveness Check

GET /live

Configuration

Configuration is managed through TOML files in the config/ directory and environment variables.

Environment Variables

Environment variables use the prefix APP_ and double underscores for nested values:

  • APP_SERVER__HOST - Server host (default: 0.0.0.0)
  • APP_SERVER__PORT - Server port (default: 8080)
  • APP_DATABASE__URL - PostgreSQL connection string
  • APP_JWT__SECRET - JWT secret key
  • APP_JWT__EXPIRATION_HOURS - Token expiration time
  • APP_CORS__ALLOWED_ORIGINS - Allowed CORS origins (comma-separated)

Configuration Files

  • config/default.toml - Default configuration
  • config/production.toml - Production overrides
  • config/local.toml - Local overrides (gitignored)

Set RUN_MODE=production to use production configuration.

Testing

Run all tests:

cargo test

Run with output:

cargo test -- --nocapture

Building for Production

Optimized Binary

cargo build --release

The optimized binary will be at target/release/rust-rest-api

Docker Image

docker build -t rust-rest-api .

Deployment

Environment Setup

  1. Set up a PostgreSQL database
  2. Configure environment variables
  3. Run database migrations
  4. Start the application

Using Docker

docker-compose -f docker-compose.yml up -d

Health Checks

Configure your orchestration platform (Kubernetes, Docker Swarm, etc.) to use:

  • Liveness: GET /live
  • Readiness: GET /ready

Security Considerations

  • Password Hashing: Uses Argon2 for secure password hashing
  • JWT Tokens: Configurable expiration time
  • SQL Injection: Protected by SQLx's compile-time query checking
  • CORS: Configurable allowed origins
  • Request Timeout: Configurable timeout to prevent resource exhaustion
  • Environment Variables: Sensitive data managed through environment variables

Performance

  • Connection Pooling: PostgreSQL connection pooling with configurable limits
  • Async Runtime: Built on Tokio for high concurrency
  • Optimized Builds: Release builds use LTO and optimization level 3
  • Binary Size: Stripped binaries for smaller deployments

Development

Adding a New Endpoint

  1. Create handler in src/api/handlers/
  2. Add route in src/api/routes.rs
  3. Add tests in tests/integration_tests.rs

Adding a New Model

  1. Create model in src/models/
  2. Create repository in src/db/
  3. Create service in src/services/
  4. Add migration in migrations/

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

Structured REST API example with Axum or Actix-Web

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •