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
Creating Rust web service boilerplate
The user wants a boilerplate for a Rust web service using actix-web and Diesel. It looks like they need files like Cargo.toml, main.rs, and a structured layout for configurations, database connections, CRUD operations, and migrations. The latest stable versions are actix-web 4.x and Diesel 2.x.
I’ll include a sample layout: Cargo.toml, a .env file, and necessary src files for configuration, database, and models. I should also mention how to use PostgreSQL and Diesel CLI commands, while keeping it concise and focused.Configuring Rust web service
I'm considering the actix-web version, possibly 4.9, but setting it as "4" will work. For Diesel, I'll use 2.2. I need to integrate actix-web with Diesel using web::Data for the pool, along with
actix_web::web::blockfor async operations.The minimal setup will include endpoints like GET /users, focusing on simplicity. I'll ensure the code compiles correctly, using Diesel's macros appropriately, and generate schema. Plus, I should note the required crate features based on the database URL.Providing setup instructions
I can lay out instructions for the user to set up Diesel CLI easily:
First, they'll need to install Diesel CLI with this command:
cargo install diesel_cli --no-default-features --features postgresNext, they'll run:
diesel setup diesel migration generate create_usersSince the user wants boilerplate, I’ll include a simple migration as a sample in the answer. I’ll format everything in markdown with headings and code blocks, starting with the
Cargo.tomlfile details for the project named "actix_diesel_boilerplate." I’ll specify the dependencies clearly without unnecessary fluff.Structuring the Rust applicationI’m mapping out the general structure for the Rust application starting with
src/main.rs. In this file, I'll initialize the logger usingenv_loggerand include modules for configuration, database, routes, models, and schema. I’ll create a database pool usingdb::init_pool(&config.database_url)and start theHttpServer.For the
configmodule, I’ll define aConfigstruct holding the host, port, and database URL. I could useanyhowfor error handling, but it might add unnecessary complexity for boilerplate code. Instead, I can stick with a simple implementation—maybe just panicking if the database URL is missing.Detailing the Rust application componentsI’m outlining the structure for the Rust application, focusing on
db.rs, which will define a type for the database pool and a function to initialize it. Inroutes.rs, I'll set up API routes such as health checks and user creation with handlers that utilize the connection pool.For
models.rs, I’ll implement data structures for users, and inschema.rs, I'll include generated content from migrations. While discussing migrations, I’ll clarify the necessary SQL for creating user tables and how to properly structure the database connection.I want to ensure the user can create and manage migrations smoothly using Diesel CLI and include guidance on the full project setup. I’ll keep things concise while ensuring clarity in how the application is structured.Structuring the Rust project for Actix and Diesel
First, I'll summarize the overall structure I’m aiming for in my Rust project using Actix and Diesel. I want to make sure we cover dependencies in
Cargo.toml, diesel configuration in.envanddiesel.toml, and then the main source files with concise code examples.I’ll illustrate the necessary setup, including implementing routes and handlers while ensuring that errors are properly managed. Let's also include a minimal migration example and offer guidance on running the project without overwhelming details. Keeping things straightforward ensures clarity for the user!Detailing Rust project configuration
Let's break down the key files for my Rust project focused on Actix and Diesel. The
Cargo.tomllists the necessary dependencies like Actix and Diesel, and I've streamlined it by removing unnecessary packages likeuuidandactix-rt.Next, I’ll outline the contents of
.envfor environment variables, anddiesel.tomlspecifying the schema file. The main logic resides insrc/main.rs, which sets up the HTTP server. I'll ensure our configuration and DB connection setup are done properly alongside route handling, including user creation and retrieval, handling errors effectively.Setting up database migrationsI'll provide the SQL needed for creating the
userstable and a simple way to drop it inup.sqlanddown.sql. After setting up the.envfile, it's essential to rundiesel setup, create the migration, and then run it. Remember, I recommend generating the schema usingdiesel print-schema > src/schema.rs, but you can use the given schema directly to avoid confusion. Also, we'll clarify steps to initialize the project, including creating the project folder and updating necessary files. Below is a minimal but complete boilerplate for an Actix‑web + Diesel web service (PostgreSQL), with a simpleUsermodel and/health,GET /users,POST /usersendpoints.
1. Project setup
cargo new actix_diesel_boilerplate --bin cd actix_diesel_boilerplateCargo.toml[package] name = "actix_diesel_boilerplate" version = "0.1.0" edition = "2021" [dependencies] actix-web = "4" serde = { version = "1", features = ["derive"] } serde_json = "1" dotenvy = "0.15" env_logger = "0.11" log = "0.4" diesel = { version = "2.2", features = ["postgres", "r2d2", "chrono"] } chrono = { version = "0.4", features = ["serde"] }
2. Diesel configuration
Install Diesel CLI (Postgres):
cargo install diesel_cli --no-default-features --features postgres.envCreate a
.envfile:DATABASE_URL=postgres://postgres:password@localhost/actix_diesel_boilerplate HOST=127.0.0.1 PORT=8080 RUST_LOG=info,actix_web=infoAdjust
DATABASE_URLto your setup.diesel.toml(optional but convenient)[print_schema] file = "src/schema.rs"Initialize database:
diesel setupCreate users migration:
diesel migration generate create_usersEdit the generated migration:
migrations/<timestamp>_create_users/up.sql:CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR NOT NULL, email VARCHAR NOT NULL UNIQUE, created_at TIMESTAMP NOT NULL DEFAULT NOW() );migrations/<timestamp>_create_users/down.sql:DROP TABLE users;Run migrations:
diesel migration runGenerate
schema.rs:diesel print-schema > src/schema.rs(You can also copy the sample
schema.rsbelow.)
3. Source files
Directory structure:
src/ main.rs config.rs db.rs models.rs routes.rs schema.rs // generated by Diesel or copied from belowsrc/main.rsmod config; mod db; mod models; mod routes; mod schema; use actix_web::{App, HttpServer}; use dotenvy::dotenv; #[actix_web::main] async fn main() -> std::io::Result<()> { // Load .env dotenv().ok(); env_logger::init(); let cfg = config::Config::from_env(); let pool = db::init_pool(&cfg.database_url); log::info!("Starting server at http://{}:{}", cfg.host, cfg.port); HttpServer::new(move || { App::new() .app_data(actix_web::web::Data::new(pool.clone())) .configure(routes::init) }) .bind((cfg.host.as_str(), cfg.port))? .run() .await }src/config.rsuse std::env; pub struct Config { pub host: String, pub port: u16, pub database_url: String, } impl Config { pub fn from_env() -> Self { let host = env::var("HOST").unwrap_or_else(|_| "127.0.0.1".to_string()); let port = env::var("PORT") .ok() .and_then(|s| s.parse().ok()) .unwrap_or(8080); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set in environment"); Self { host, port, database_url, } } }src/db.rsuse diesel::pg::PgConnection; use diesel::r2d2::{self, ConnectionManager}; pub type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>; pub fn init_pool(database_url: &str) -> DbPool { let manager = ConnectionManager::<PgConnection>::new(database_url); r2d2::Pool::builder() .build(manager) .expect("Failed to create DB connection pool") }src/models.rsuse crate::schema::users; use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Queryable)] pub struct User { pub id: i32, pub name: String, pub email: String, pub created_at: NaiveDateTime, } #[derive(Debug, Deserialize, Insertable)] #[diesel(table_name = users)] pub struct NewUser { pub name: String, pub email: String, }src/routes.rsuse crate::db::DbPool; use crate::models::{NewUser, User}; use crate::schema::users::dsl::*; use actix_web::{get, post, web, HttpResponse, Responder}; use diesel::prelude::*; #[get("/health")] async fn health_check() -> impl Responder { HttpResponse::Ok().json(serde_json::json!({ "status": "ok" })) } #[post("/users")] async fn create_user(pool: web::Data<DbPool>, payload: web::Json<NewUser>) -> impl Responder { let new_user = payload.into_inner(); let pool = pool.clone(); let result = web::block(move || { let mut conn = pool .get() .expect("couldn't get db connection from pool"); diesel::insert_into(users) .values(&new_user) .get_result::<User>(&mut conn) }) .await; match result { Ok(Ok(user)) => HttpResponse::Created().json(user), Ok(Err(e)) => { log::error!("DB error creating user: {}", e); HttpResponse::InternalServerError().finish() } Err(e) => { log::error!("Blocking error creating user: {}", e); HttpResponse::InternalServerError().finish() } } } #[get("/users")] async fn list_users(pool: web::Data<DbPool>) -> impl Responder { let pool = pool.clone(); let result = web::block(move || { let mut conn = pool .get() .expect("couldn't get db connection from pool"); users .order(id.asc()) .load::<User>(&mut conn) }) .await; match result { Ok(Ok(user_list)) => HttpResponse::Ok().json(user_list), Ok(Err(e)) => { log::error!("DB error listing users: {}", e); HttpResponse::InternalServerError().finish() } Err(e) => { log::error!("Blocking error listing users: {}", e); HttpResponse::InternalServerError().finish() } } } pub fn init(cfg: &mut web::ServiceConfig) { cfg.service(health_check) .service(create_user) .service(list_users); }src/schema.rsIf you used
diesel print-schema > src/schema.rs, it should look like this:// @generated automatically by Diesel CLI. diesel::table! { users (id) { id -> Int4, name -> Varchar, email -> Varchar, created_at -> Timestamp, } }
4. Run the service
Make sure Postgres is running and
DATABASE_URLpoints to a valid DB.cargo runEndpoints:
GET /health→{"status":"ok"}GET /users→ list of usersPOST /userswith JSON body:{ "name": "Alice", "email": "alice@example.com" }
If you want, I can extend this boilerplate with structured error types, tests, or a more complete CRUD example.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.