Skip to content
TheChatArchiveThe Chat Archive
GeminiGemini 3 Pro Preview· googleHugging Face Frontier Reasoning Traces

Create a boilerplate for a Rust web service using Actix-web and Diesel.

  1. User

    Create a boilerplate for a Rust web service using Actix-web and Diesel.

  2. Gemini 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, and routes.rs for database interaction and API endpoints. The entry point, main.rs, will serve as the conductor. Dependencies include actix-web, diesel (Postgres and r2d2 features), dotenvy, and serde. PostgreSQL is the primary database choice.

    Coding the Foundation

    I'm now actively writing the code, starting with models.rs and the necessary traits: Queryable, Selectable, Insertable, and Serialize/Deserialize are all essential. Next, I'm focusing on db.rs to set up the connection pool using r2d2. The aim is to make it easy to use in conjunction with dotenv. Currently, I am also drafting the handlers for the user routes in routes.rs. My goal is to ensure database operations don't block the async runtime using web::block. Finally, I'm working on main.rs to 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 using unwrap(). To simplify user understanding, I'm sticking with i32 for 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-web and diesel version compatibility. The framework is using App::new() and HttpServer::new(), while Diesel aligns with the 2.x syntax. I also double-checked all the necessary imports from diesel::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

    1. Rust & Cargo: Installed via rustup.
    2. PostgreSQL: Installed and running.
    3. 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_diesel
    

    Cargo.toml Add 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

    1. Create a .env file in the root directory:

      DATABASE_URL=postgres://username:password@localhost/actix_diesel_db
      RUST_LOG=info
      HOST=127.0.0.1
      PORT=8080
      
    2. Setup Diesel:

      diesel setup
      diesel migration generate create_users
      
    3. 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()
      );
      
    4. Edit the down.sql in the same folder:

      DROP TABLE users;
      
    5. Run the migration:

      diesel migration run
      

    3. Project Structure

    Refactor your src folder 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.rs

    Define 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.rs

    Setup 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.rs

    Your API endpoints. Note that we use web::block to 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.rs

    The 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

    1. Run the server:

      cargo run
      
    2. 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 Data to share the DB pool across threads.
    • Non-Blocking: Uses web::block to ensure synchronous code (Diesel) doesn't stop the async server (Actix).
    • Connection Pooling: r2d2 manages connections efficiently for high loads.
    • Type Safety: Diesel checks your SQL schema against your Rust structs at compile time.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.