A clean, scalable, and production-ready backend template built with Rust and Axum framework.
- 🚀 Axum Framework - Fast, ergonomic web framework
- 🏗️ Clean Architecture - Layered architecture with handlers, services, and repositories
- 🔒 JWT Authentication - Secure user authentication and authorization
- 🗄️ PostgreSQL Integration - Database operations with SQLx
- 🔧 Configuration Management - Environment-based configuration
- 📝 Comprehensive Logging - Structured logging with tracing
- 🐳 Docker Support - Full containerization with Docker Compose
- 🧪 Testing Framework - Unit and integration tests
- 📊 Health Checks - Application health monitoring
- 🌐 CORS Support - Cross-origin resource sharing
- 📦 Error Handling - Comprehensive error handling system
- 📖 Swagger UI - Interactive API documentation with OpenAPI 3.0
rust-backend-template/
├── src/
│ ├── handlers/ # HTTP request handlers
│ │ ├── auth.rs # Authentication endpoints
│ │ ├── health.rs # Health check endpoint
│ │ ├── users.rs # User CRUD endpoints
│ │ └── mod.rs
│ ├── services/ # Business logic layer
│ │ ├── user.rs # User business logic
│ │ └── mod.rs
│ ├── repositories/ # Data access layer
│ │ ├── user.rs # User database operations
│ │ └── mod.rs
│ ├── models/ # Data models and DTOs
│ │ ├── user.rs # User models
│ │ └── mod.rs
│ ├── middleware/ # Custom middleware
│ │ ├── auth.rs # Authentication middleware
│ │ └── mod.rs
│ ├── utils/ # Utility functions
│ │ ├── database.rs # Database utilities
│ │ ├── jwt.rs # JWT utilities
│ │ ├── password.rs # Password hashing
│ │ └── mod.rs
│ ├── config.rs # Configuration management
│ ├── errors.rs # Error types and handling
│ ├── swagger.rs # Swagger/OpenAPI configuration
│ └── main.rs # Application entry point
├── migrations/ # Database migrations
├── tests/ # Integration tests
├── docker-compose.yml # Docker services
├── Dockerfile # Container definition
├── deploy.sh # Deployment script
└── README.md
- Rust 1.75+
- PostgreSQL 15+
- Docker & Docker Compose (optional)
-
Clone the repository
git clone <your-repo-url> cd rust-backend-template
-
Run with Docker
./deploy.sh
This will:
- Build the application
- Start PostgreSQL and Redis
- Run database migrations
- Start the backend server
-
Access the API
- API: http://localhost:3000
- Health: http://localhost:3000/api/v1/health
- Swagger UI: http://localhost:3000/swagger-ui/
- OpenAPI JSON: http://localhost:3000/api-docs/openapi.json
-
Setup Environment
cp .env.example .env # Edit .env with your configuration -
Start PostgreSQL
docker run --name postgres -e POSTGRES_PASSWORD=password -e POSTGRES_DB=rust_backend -p 5432:5432 -d postgres:15
-
Run Migrations
cargo install sqlx-cli sqlx migrate run
-
Start the Application
cargo run
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/health |
Health check |
| POST | /api/v1/auth/register |
Register new user |
| POST | /api/v1/auth/login |
Login user |
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/users/me |
Get current user |
| PUT | /api/v1/users/me |
Update current user |
| DELETE | /api/v1/users/me |
Delete current user |
| GET | /api/v1/users |
List all users |
| GET | /api/v1/users/:id |
Get user by ID |
| PUT | /api/v1/users/:id |
Update user by ID |
| DELETE | /api/v1/users/:id |
Delete user by ID |
The API uses JWT (JSON Web Tokens) for authentication.
curl -X POST http://localhost:3000/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "password123",
"full_name": "John Doe"
}'curl -X POST http://localhost:3000/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "password123"
}'curl -X GET http://localhost:3000/api/v1/users/me \
-H "Authorization: Bearer YOUR_JWT_TOKEN"The API comes with interactive Swagger UI documentation:
- Swagger UI: http://localhost:3000/swagger-ui/
- OpenAPI JSON: http://localhost:3000/api-docs/openapi.json
Features:
- 🔍 Interactive API explorer
- 🔐 Built-in JWT authentication testing
- 📝 Request/response examples
- 🎯 Try-it-out functionality
- 📋 Model schemas with validation rules
To use protected endpoints in Swagger:
- Register/Login to get a JWT token
- Click "Authorize" button in Swagger UI
- Enter:
Bearer YOUR_JWT_TOKEN - Now you can test protected endpoints
The application is configured through environment variables:
| Variable | Description | Default |
|---|---|---|
DATABASE_URL |
PostgreSQL connection string | postgresql://localhost:5432/rust_backend |
JWT_SECRET |
Secret key for JWT signing | your-super-secret-jwt-key |
JWT_EXPIRES_IN |
JWT expiration time | 24h |
PORT |
Server port | 3000 |
CORS_ORIGIN |
CORS allowed origins | * |
ENVIRONMENT |
Runtime environment | development |
LOG_LEVEL |
Logging level | info |
cargo test# Setup test database
export DATABASE_URL=postgresql://localhost:5432/rust_backend_test
sqlx database create
sqlx migrate run
# Run tests
cargo test --test integration_tests# Build and start all services
docker-compose up --build -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
# Restart services
docker-compose restart
# Execute commands in container
docker-compose exec backend bash# Install SQLx CLI
cargo install sqlx-cli
# Create new migration
sqlx migrate add create_users_table
# Run migrations
sqlx migrate run
# Revert last migration
sqlx migrate revert- Create Model in
src/models/ - Create Repository in
src/repositories/ - Create Service in
src/services/ - Create Handlers in
src/handlers/ - Add Routes to main router
- Write Tests in
tests/
# Format code
cargo fmt
# Lint code
cargo clippy
# Check for security vulnerabilities
cargo audit-
Build optimized image
docker build -t rust-backend:prod . -
Set production environment variables
export ENVIRONMENT=production export JWT_SECRET=your-production-secret export DATABASE_URL=your-production-db-url
-
Deploy with docker-compose
docker-compose -f docker-compose.prod.yml up -d
The application includes health checks at /api/v1/health that return:
{
"status": "ok",
"message": "Service is healthy",
"timestamp": "2023-10-01T12:00:00Z"
}- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Happy coding! 🦀✨