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! π¦β¨