A boilerplate for building scalable and production-ready REST APIs in Rust using Actix-Web and SQLx with PostgreSQL. This project demonstrates a modular structure with best practices for managing configurations, routes, database connections, and more.
- Actix-Web: High-performance web framework.
- SQLx: Async, compile-time verified SQL queries.
- PostgreSQL: Persistent database support.
- Environment Variables: Configurable using
.env
. - Dockerized: Docker support for the application and PostgreSQL.
- Migrations: Database migrations with
sqlx-cli
. - Structured Code: Modular design for scalability.
├── Cargo.toml # Rust dependencies and project metadata
├── Dockerfile # Dockerfile for building the app container
├── docker-compose.yml # Docker Compose setup for API and database
├── migrations/ # SQL migration files for database schema
├── src/
│ ├── config.rs # Environment variable management
│ ├── db.rs # Database connection pool setup
│ ├── handlers/ # Request handlers
│ ├── models/ # Data models and DTOs
│ ├── routes/ # API route configurations
│ ├── services/ # Business logic and database operations
│ └── main.rs # Application entry point
git clone https://github.com/your-username/rust-api-boilerplate.git
cd rust-api-boilerplate
Ensure Docker is installed and running, then execute:
docker-compose up --build
This command starts the API and a PostgreSQL database.
- Base URL:
http://127.0.0.1:8080
- Example Endpoints:
GET /hello
: Health check.GET /users
: Fetch all users.POST /users
: Create a new user.
- Rust (latest stable version)
- PostgreSQL (installed and running)
sqlx-cli
for database migrations:cargo install sqlx-cli
Create a .env
file in the project root:
DATABASE_URL=postgres://user:password@localhost:5432/rustdb
PORT=8080
Run migrations to set up the database schema:
sqlx migrate run
Start the server locally:
cargo run
Access the API at http://127.0.0.1:8080
.
- GET /hello
- Description: Simple endpoint to verify the API is working.
- Response:
"Hello, World!"
-
GET /users
- Description: Retrieve all users.
- Response:
[ { "id": "uuid", "name": "John Doe", "email": "john.doe@example.com" } ]
-
POST /users
- Description: Create a new user.
- Request Body:
{ "name": "Jane Doe", "email": "jane.doe@example.com" }
- Response:
{ "id": "uuid", "name": "Jane Doe", "email": "jane.doe@example.com" }
Variable | Default | Description |
---|---|---|
DATABASE_URL |
None | PostgreSQL connection string |
PORT |
8080 |
Port where the API runs |
To run tests (if implemented):
cargo test
-
Build the Docker Image:
docker build -t rust-api-boilerplate .
-
Run the Container:
docker run -d --env-file .env -p 8080:8080 rust-api-boilerplate
-
Push to Docker Hub (optional):
docker tag rust-api-boilerplate your-username/rust-api-boilerplate:latest docker push your-username/rust-api-boilerplate:latest