Create a boilerplate for a Rust web service using Actix-web and Diesel.
- User
Create a boilerplate for a Rust web service using Actix-web and Diesel.
Assistant
Refining the Blueprint
I'm zeroing in on the core components for this Rust web service boilerplate. My focus is now on the framework - Actix-web - and its interplay with an ORM. The goal is to make the resulting code as lean and extendable as possible.
Developing the Core Features
I'm now integrating Diesel as the ORM, focusing on how it meshes with Actix-web. I'm prioritizing essential features for a solid boilerplate: a robust project structure, proper dependency management, environment variable handling, database connection pooling, basic CRUD operation examples, error handling strategies, and a functional migration system. My plan is to implement this systematically, starting with prerequisites and moving through project setup, dependency installation, and finally, database configuration.
Defining the Architecture
I'm now concretizing the project's structure, focusing on a clear module breakdown. I've drafted
models.rs,schema.rs,db.rs, androutes.rsfor database interaction and API endpoints. The entry point,main.rs, will serve as the conductor. Dependencies includeactix-web,diesel(Postgres and r2d2 features),dotenvy, andserde. PostgreSQL is the primary database choice.Coding the Foundation
I'm now actively writing the code, starting with
models.rsand the necessary traits:Queryable,Selectable,Insertable, andSerialize/Deserializeare all essential. Next, I'm focusing ondb.rsto set up the connection pool usingr2d2. The aim is to make it easy to use in conjunction withdotenv. Currently, I am also drafting the handlers for the user routes inroutes.rs. My goal is to ensure database operations don't block the async runtime usingweb::block. Finally, I'm working onmain.rsto load the environment variables, set up the logger, initialize the pool, and configure the HTTP server.Finalizing the Boilerplate
I'm now integrating the database migration workflow and explicitly illustrating the SQL migration file to guide users. I've switched to the
?operator for error handling where applicable, while also briefly covering the trade-offs of usingunwrap(). To simplify user understanding, I'm sticking withi32for IDs, but I've included a note on the common usage of UUIDs. The documentation is also well underway.Confirming the Syntax
I've just confirmed the syntax for
actix-webanddieselversion compatibility. The framework is usingApp::new()andHttpServer::new(), while Diesel aligns with the 2.x syntax. I also double-checked all the necessary imports fromdiesel::prelude::*.Here is a comprehensive boilerplate for a REST API using Rust, Actix-web (v4), and Diesel (v2) with PostgreSQL.
This setup includes database connection pooling, environment variable configuration, and a modular structure suitable for scaling.
Prerequisites
- Rust & Cargo: Installed via rustup.
- PostgreSQL: Installed and running.
- Diesel CLI: Installed with postgres support:
cargo install diesel_cli --no-default-features --features postgres
1. Project Initialization & Dependencies
Create the project and update
Cargo.toml.cargo new rust_actix_diesel cd rust_actix_dieselCargo.tomlAdd the following dependencies to handle the web server, database ORM, serialization, and environment variables.[package] name = "rust_actix_diesel" version = "0.1.0" edition = "2021" [dependencies] # Web Framework actix-web = "4" # Database & ORM diesel = { version = "2.1", features = ["postgres", "r2d2", "chrono"] } # Serialization serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" # Environment & Logging dotenvy = "0.15" env_logger = "0.10"
2. Database Setup
-
Create a
.envfile in the root directory:DATABASE_URL=postgres://username:password@localhost/actix_diesel_db RUST_LOG=info HOST=127.0.0.1 PORT=8080 -
Setup Diesel:
diesel setup diesel migration generate create_users -
Edit the generated SQL file in
migrations/YYYY-MM-DD-XXXXXX_create_users/up.sql:CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR NOT NULL, email VARCHAR NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW() ); -
Edit the
down.sqlin the same folder:DROP TABLE users; -
Run the migration:
diesel migration run
3. Project Structure
Refactor your
srcfolder to look like this to ensure clean separation of concerns:src/ ├── main.rs ├── schema.rs // Auto-generated by Diesel ├── models.rs // Structs mapping to DB tables ├── db.rs // Database connection logic └── services.rs // HTTP Route Handlers
4. The Code
src/models.rsDefine the data structures. We need one struct that represents the row in the DB and one for inserting a new row.
use diesel::prelude::*; use serde::{Deserialize, Serialize}; use crate::schema::users; #[derive(Queryable, Selectable, Serialize)] #[diesel(table_name = users)] #[diesel(check_for_backend(diesel::pg::Pg))] pub struct User { pub id: i32, pub name: String, pub email: String, pub created_at: chrono::NaiveDateTime, } #[derive(Insertable, Deserialize)] #[diesel(table_name = users)] pub struct NewUser { pub name: String, pub email: String, }src/db.rsSetup the connection pool (using
r2d2). This allows multiple requests to share database connections efficiently.use diesel::pg::PgConnection; use diesel::r2d2::ConnectionManager; use r2d2::Pool; use std::env; pub type DbPool = Pool<ConnectionManager<PgConnection>>; pub fn establish_connection() -> DbPool { let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let manager = ConnectionManager::<PgConnection>::new(database_url); Pool::builder() .build(manager) .expect("Failed to create pool.") }src/services.rsYour API endpoints. Note that we use
web::blockto offload blocking database operations to a thread pool, preventing the async web server from freezing.use actix_web::{get, post, web, HttpResponse, Responder}; use diesel::prelude::*; use crate::{db::DbPool, models::{NewUser, User}, schema::users}; #[get("/users")] pub async fn get_users(pool: web::Data<DbPool>) -> impl Responder { // Offload the blocking DB operation to a thread pool let users = web::block(move || { let mut conn = pool.get().expect("couldn't get db connection from pool"); users::table.load::<User>(&mut conn) }) .await; match users { Ok(Ok(users)) => HttpResponse::Ok().json(users), _ => HttpResponse::InternalServerError().json("Error retrieving users"), } } #[post("/users")] pub async fn create_user( pool: web::Data<DbPool>, payload: web::Json<NewUser>, ) -> impl Responder { let new_user = payload.into_inner(); let user = web::block(move || { let mut conn = pool.get().expect("couldn't get db connection from pool"); diesel::insert_into(users::table) .values(&new_user) .returning(User::as_returning()) .get_result(&mut conn) }) .await; match user { Ok(Ok(user)) => HttpResponse::Ok().json(user), _ => HttpResponse::InternalServerError().json("Error inserting user"), } } // Combine routes for easy registration in main pub fn config(cfg: &mut web::ServiceConfig) { cfg.service(get_users); cfg.service(create_user); }src/main.rsThe entry point creates the app, loads environment variables, creates the DB pool, and starts the server.
mod db; mod models; mod schema; mod services; use actix_web::{web, App, HttpServer}; use dotenvy::dotenv; use std::env; #[actix_web::main] async fn main() -> std::io::Result<()> { // 1. Initial setup dotenv().ok(); env_logger::init(); // 2. Create DB Pool let pool = db::establish_connection(); // 3. Fetch host and port let host = env::var("HOST").unwrap_or_else(|_| "127.0.0.1".to_string()); let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string()); let addr = format!("{}:{}", host, port); println!("Server running at http://{}", addr); // 4. Start HTTP Server HttpServer::new(move || { App::new() // Pass the DB pool to all routes .app_data(web::Data::new(pool.clone())) .configure(services::config) }) .bind(addr)? .run() .await }
5. Running and Testing
-
Run the server:
cargo run -
Test with CURL (or Postman):
-
Create a User:
curl -X POST http://127.0.0.1:8080/users \ -H "Content-Type: application/json" \ -d '{"name": "Alice", "email": "alice@example.com"}' -
Get Users:
curl http://127.0.0.1:8080/users
-
Key Features of this Boilerplate:
- Thread Safety: Uses Actix
Datato share the DB pool across threads. - Non-Blocking: Uses
web::blockto ensure synchronous code (Diesel) doesn't stop the async server (Actix). - Connection Pooling:
r2d2manages connections efficiently for high loads. - Type Safety: Diesel checks your SQL schema against your Rust structs at compile time.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.