A production-ready REST API built with Rust and Axum, featuring authentication, database integration, comprehensive error handling, and Docker support.
- 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
validatorcrate - Structured Logging: Request tracing and logging with
tracingandtracing-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
.
├── 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
- Rust 1.75 or later
- PostgreSQL 14 or later
- Docker and Docker Compose (optional)
- Clone the repository
git clone https://github.com/yourusername/rust-rest-api.git
cd rust-rest-api- Set up environment variables
cp .env.example .env
# Edit .env with your configuration- 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- Run migrations
cargo install sqlx-cli --no-default-features --features postgres
sqlx migrate run- Run the application
cargo runThe API will be available at http://localhost:8080
docker-compose up -dThis will start both the PostgreSQL database and the API service.
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"
}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"
}
}All user endpoints require authentication. Include the JWT token in the Authorization header:
Authorization: Bearer <your-jwt-token>
GET /api/v1/users?page=1&per_page=10Response:
{
"data": [...],
"total": 100,
"page": 1,
"per_page": 10,
"total_pages": 10
}GET /api/v1/users/{id}GET /api/v1/users/mePUT /api/v1/users/{id}
Content-Type: application/json
{
"email": "[email protected]",
"username": "newusername"
}DELETE /api/v1/users/{id}GET /healthGET /readyGET /liveConfiguration is managed through TOML files in the config/ directory and 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 stringAPP_JWT__SECRET- JWT secret keyAPP_JWT__EXPIRATION_HOURS- Token expiration timeAPP_CORS__ALLOWED_ORIGINS- Allowed CORS origins (comma-separated)
config/default.toml- Default configurationconfig/production.toml- Production overridesconfig/local.toml- Local overrides (gitignored)
Set RUN_MODE=production to use production configuration.
Run all tests:
cargo testRun with output:
cargo test -- --nocapturecargo build --releaseThe optimized binary will be at target/release/rust-rest-api
docker build -t rust-rest-api .- Set up a PostgreSQL database
- Configure environment variables
- Run database migrations
- Start the application
docker-compose -f docker-compose.yml up -dConfigure your orchestration platform (Kubernetes, Docker Swarm, etc.) to use:
- Liveness:
GET /live - Readiness:
GET /ready
- 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
- 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
- Create handler in
src/api/handlers/ - Add route in
src/api/routes.rs - Add tests in
tests/integration_tests.rs
- Create model in
src/models/ - Create repository in
src/db/ - Create service in
src/services/ - Add migration in
migrations/
MIT
Contributions are welcome! Please feel free to submit a Pull Request.