Fast Developer Reference

Actix Web Cheatsheet

Copy-pasteable code snippets for common Actix Web patterns: extractors, state injection, CORS, custom headers, and JSON error responders.

Server Initialization

Basic Async Server with Workers

Standard production listener binding to all network interfaces on port 8080 with worker threads.

Rust Code
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(index)
    })
    .workers(4)
    .bind(("0.0.0.0", 8080))?
    .run()
    .await
}
Extractors

Path & Query Parameter Extraction

Type-safe extraction of URL path variables and query strings into Rust structs or HashMaps.

Rust Code
#[get("/users/{id}")]
async fn get_user(
    path: web::Path<u64>,
    query: web::Query<HashMap<String, String>>,
) -> impl Responder {
    let user_id = path.into_inner();
    format!("User ID: {}, Query: {:?}", user_id, query)
}
Extractors

JSON Body Deserialization

Automatically parse incoming request application/json payloads into typed structs.

Rust Code
#[derive(Deserialize)]
struct CreateItem {
    name: String,
    price: f64,
}

#[post("/items")]
async fn create_item(body: web::Json<CreateItem>) -> impl Responder {
    HttpResponse::Created().json(body.into_inner())
}
State Management

Shared Database Pool Injection

Inject thread-safe database pools into application state using Arc-wrapped web::Data.

Rust Code
let pool = PgPoolOptions::new().connect(&db_url).await?;

HttpServer::new(move || {
    App::new()
        .app_data(web::Data::new(pool.clone()))
        .service(handler)
})
Middleware

CORS & Structured Logger

Attach access logging and permissive cross-origin resource sharing middleware.

Rust Code
use actix_cors::Cors;
use actix_web::middleware::Logger;

App::new()
    .wrap(Logger::default())
    .wrap(Cors::permissive())
Error Handling

Standard JSON Error Responder

Standardized JSON error envelope helper functions.

Rust Code
#[derive(Serialize)]
struct ErrorEnvelope {
    error: String,
    code: u16,
}

fn bad_request_error(msg: &str) -> HttpResponse {
    HttpResponse::BadRequest().json(ErrorEnvelope {
        error: msg.to_string(),
        code: 400,
    })
}

Need Full Production Rust Boilerplates?

Get complete downloadable SaaS repositories with SQLx, JWT auth, Stripe billing, and Distroless Docker files.

Explore Actix Pro