Actix-web Tutorial: A Fast Rust API for Shop Orders

Quick answer

Actix-web is a Rust web framework built for speed, with a routing and extractor system that turns HTTP requests into typed Rust values. This post builds a small shop orders API with it: POST /orders takes a customer and a list of items, checks each item against a price list, and returns the order with the total worked out. GET /orders lists every order the shop has taken.

A small clothing shop in Karachi takes orders over WhatsApp. The owner reads each message, copies the items into a notebook, and works out the total on a calculator. It works until a busy evening arrives: one order copied with the wrong quantity, one total added up wrong, one customer asking where her order is while nobody can find it in the notebook. The shop needs one place where an order is recorded once, the items are checked against real prices, and the total is worked out the same way every time. Actix-web fits that job, because it is fast, typed, and small enough to learn in an afternoon, and this post builds that API with it.

What I would check before using it

My first check is whether the team is comfortable with Rust. Actix-web is a Rust framework, so the borrow checker and the type system come with it. If the team already writes Rust, that is a strength; if not, the first week will be slower than a framework in a language the team knows.

My second check is async. Actix-web runs on Tokio, so handlers are async functions and shared state lives behind a lock or an actor. If the team has never written async Rust, start with one small endpoint and learn the patterns there.

My third check is the ecosystem around it. Actix-web is mature, on version 4, with middleware for logging, compression, and sessions. If the project needs only routing and a JSON body, a lighter framework such as Axum may fit better, and the Axum Tutorial: Build a Rust API Without the Boilerplate post shows that route.

My fourth check is how the API will grow. Actix-web handles a single service well, and its actor system suits background jobs. If the plan is many small services, the deployment story matters more than the framework, so check that first.

My verdict, as judgement: choose Actix-web for a Rust API where speed and a complete feature set matter, and the team is willing to learn async Rust. It flips when the team wants the lightest possible stack, or when a prototype could ride on Gin in a language the team already knows.

A Karachi clothing shop, served by Actix-web

The demo is the Karachi clothing shop from the intro: three products, a price list, and an API that takes an order and works out the total.

Create the project and add the dependencies:

[package]
name = "shop_orders"
version = "0.1.0"
edition = "2021"

[dependencies]
actix-web = "4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Code lives in src/main.rs. The state holds the orders in a Mutex and the next order id, and the price list is a small match with three products. POST /orders checks the items, works out the total, and returns the order with a 201 status; GET /orders returns the whole list:

use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};
use std::sync::Mutex;

#[derive(Serialize, Clone)]
struct OrderItem {
    name: String,
    price_rs: u32,
    qty: u32,
}

#[derive(Serialize, Clone)]
struct Order {
    id: u32,
    customer: String,
    items: Vec<OrderItem>,
    total_rs: u32,
}

#[derive(Deserialize)]
struct NewItem {
    name: String,
    qty: u32,
}

#[derive(Deserialize)]
struct NewOrder {
    customer: String,
    items: Vec<NewItem>,
}

struct AppState {
    orders: Mutex<Vec<Order>>,
    next_id: Mutex<u32>,
}

fn price_rs(name: &str) -> Option<u32> {
    match name {
        "White Cotton Kurta" => Some(2450),
        "Navy Blue Shalwar Kameez" => Some(3200),
        "Pastel Lawn Kurta" => Some(1950),
        _ => None,
    }
}

#[post("/orders")]
async fn create_order(
    data: web::Data<AppState>,
    body: web::Json<NewOrder>,
) -> impl Responder {
    if body.items.is_empty() {
        return HttpResponse::BadRequest().body("order needs at least one item");
    }
    let mut items = Vec::new();
    let mut total_rs = 0;
    for item in &body.items {
        match price_rs(&item.name) {
            Some(price) => {
                total_rs += price * item.qty;
                items.push(OrderItem {
                    name: item.name.clone(),
                    price_rs: price,
                    qty: item.qty,
                });
            }
            None => {
                return HttpResponse::BadRequest()
                    .body(format!("unknown product: {}", item.name));
            }
        }
    }
    let mut next_id = data.next_id.lock().unwrap();
    let order = Order {
        id: *next_id,
        customer: body.customer.clone(),
        items,
        total_rs,
    };
    *next_id += 1;
    data.orders.lock().unwrap().push(order.clone());
    HttpResponse::Created().json(order)
}

#[get("/orders")]
async fn list_orders(data: web::Data<AppState>) -> impl Responder {
    let orders = data.orders.lock().unwrap();
    HttpResponse::Ok().json(&*orders)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let state = web::Data::new(AppState {
        orders: Mutex::new(Vec::new()),
        next_id: Mutex::new(1),
    });
    println!("Actix-web shop orders API listening on http://127.0.0.1:8080");
    HttpServer::new(move || {
        App::new()
            .app_data(state.clone())
            .service(create_order)
            .service(list_orders)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

Run it:

$ cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.27s
     Running `target/debug/shop_orders`
Actix-web shop orders API listening on http://127.0.0.1:8080

The list starts empty:

$ curl -s http://127.0.0.1:8080/orders
[]

Now place an order for Ayesha: one White Cotton Kurta, two Navy Blue Shalwar Kameez, two Pastel Lawn Kurta. My first attempt sent the quantity as a string, "qty": "2", copied from a WhatsApp message where everything is text:

$ curl -s -X POST http://127.0.0.1:8080/orders \
  -H "Content-Type: application/json" \
  -d '{"customer":"Ayesha","items":[{"name":"White Cotton Kurta","qty":"2"}]}'
Json deserialize error: invalid type: string "2", expected u32 at line 1 column 68

The JSON extractor rejected the request before the handler ran, with HTTP 400. It expects a number for qty, because the struct says u32, and a string is not a number. The fix is at the data: send 2, not "2".

$ curl -s -X POST http://127.0.0.1:8080/orders \
  -H "Content-Type: application/json" \
  -d '{"customer":"Ayesha","items":[{"name":"White Cotton Kurta","qty":1},{"name":"Navy Blue Shalwar Kameez","qty":2},{"name":"Pastel Lawn Kurta","qty":2}]}'
{"id":1,"customer":"Ayesha","items":[{"name":"White Cotton Kurta","price_rs":2450,"qty":1},{"name":"Navy Blue Shalwar Kameez","price_rs":3200,"qty":2},{"name":"Pastel Lawn Kurta","price_rs":1950,"qty":2}],"total_rs":12750}

HTTP status: 201. Rs 2,450 once, plus Rs 3,200 twice, plus Rs 1,950 twice, comes to Rs 12,750. GET /orders shows the order stored:

$ curl -s http://127.0.0.1:8080/orders
[{"id":1,"customer":"Ayesha","items":[{"name":"White Cotton Kurta","price_rs":2450,"qty":1},{"name":"Navy Blue Shalwar Kameez","price_rs":3200,"qty":2},{"name":"Pastel Lawn Kurta","price_rs":1950,"qty":2}],"total_rs":12750}]

One order in, one order out, and the total was worked out by the server, not by a calculator.

Terminal output showing an Actix-web JSON error on a string quantity, then the fixed order returning total Rs 12,750 and GET /orders listing it.

Common mistakes and how to fix them

First, sending a number as a string in the JSON body, like "qty": "2". The extractor answers: "Json deserialize error: invalid type: string "2", expected u32 at line 1 column 68", with HTTP 400. The fix is a bare number, 2, because the struct field is a u32.

Second, mistyping the route, for example GET /order instead of GET /orders. The server answers with HTTP 404 and no body. Routes match exactly, so check the spelling and the plural before blaming the server.

Third, ordering a product that is not in the price list, like a Silk Sherwani. The handler answers: "unknown product: Silk Sherwani", with HTTP 400. The fix is at the data: add the product to price_rs, or correct the spelling.

Fourth, posting an order with no items at all. The handler answers: "order needs at least one item", with HTTP 400. The fix is to validate on the client too, so an empty cart never reaches the server.

Frequently Asked Questions

Is Actix-web faster than Axum? Both are fast, and published benchmarks put them close together, so speed alone rarely decides it. Pick on ergonomics: Actix-web is a complete framework with middleware included, while Axum stays closer to bare routing. The Axum Tutorial: Build a Rust API Without the Boilerplate post shows the other side.

Do I need to know async Rust to use Actix-web? The basics, yes. Handlers are async fn, you await the work, and the server runs on Tokio. One small endpoint is enough to learn the shape.

Can Actix-web serve a website, or only APIs? Both. It serves static files and templates, and this post sticks to the API side. If you come from Node, the Koa Tutorial: Build a Node.js Orders API From Scratch post builds the same kind of API in JavaScript.

Is Actix-web still maintained? Yes. Version 4 is the current line, this post ran actix-web 4.20.0, and releases continue. Check the changelog before starting a new project.

What to remember

  • Actix-web turns HTTP requests into typed Rust values through extractors, and a wrong type fails before the handler runs.
  • Keep money in whole rupees as integers, and the server works out the total the same way every time.
  • POST /orders validates each item against a price list and returns 201 with the stored order.
  • GET /orders lists every order the shop has taken.
  • Routes match exactly: /order is not /orders, and the server answers 404.

Where this leaves you

One small server, two routes, and the shop now has an order recorded once, checked against real prices, and totalled to Rs 12,750 without a calculator in sight. The JSON error was the useful part: the extractor would rather reject a bad request than let a wrong quantity reach the total. Take an order flow of your own, the kind still living in a notebook or a chat thread, and give it two routes before you give it a frontend.

Further reading

Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

Quick answer

Actix-web is a Rust web framework built for speed, with a routing and extractor system that turns HTTP requests into typed Rust values. This post builds a small shop orders API with it: POST /orders takes a customer and a list of items, checks each item against a price list, and returns the order with the total worked out. GET /orders lists every order the shop has taken.

A small clothing shop in Karachi takes orders over WhatsApp. The owner reads each message, copies the items into a notebook, and works out the total on a calculator. It works until a busy evening arrives: one order copied with the wrong quantity, one total added up wrong, one customer asking where her order is while nobody can find it in the notebook. The shop needs one place where an order is recorded once, the items are checked against real prices, and the total is worked out the same way every time. Actix-web fits that job, because it is fast, typed, and small enough to learn in an afternoon, and this post builds that API with it.

What I would check before using it

My first check is whether the team is comfortable with Rust. Actix-web is a Rust framework, so the borrow checker and the type system come with it. If the team already writes Rust, that is a strength; if not, the first week will be slower than a framework in a language the team knows.

My second check is async. Actix-web runs on Tokio, so handlers are async functions and shared state lives behind a lock or an actor. If the team has never written async Rust, start with one small endpoint and learn the patterns there.

My third check is the ecosystem around it. Actix-web is mature, on version 4, with middleware for logging, compression, and sessions. If the project needs only routing and a JSON body, a lighter framework such as Axum may fit better, and the Axum Tutorial: Build a Rust API Without the Boilerplate post shows that route.

My fourth check is how the API will grow. Actix-web handles a single service well, and its actor system suits background jobs. If the plan is many small services, the deployment story matters more than the framework, so check that first.

My verdict, as judgement: choose Actix-web for a Rust API where speed and a complete feature set matter, and the team is willing to learn async Rust. It flips when the team wants the lightest possible stack, or when a prototype could ride on Gin in a language the team already knows.

A Karachi clothing shop, served by Actix-web

The demo is the Karachi clothing shop from the intro: three products, a price list, and an API that takes an order and works out the total.

Create the project and add the dependencies:

[package]
name = "shop_orders"
version = "0.1.0"
edition = "2021"

[dependencies]
actix-web = "4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Code lives in src/main.rs. The state holds the orders in a Mutex and the next order id, and the price list is a small match with three products. POST /orders checks the items, works out the total, and returns the order with a 201 status; GET /orders returns the whole list:

use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};
use std::sync::Mutex;

#[derive(Serialize, Clone)]
struct OrderItem {
    name: String,
    price_rs: u32,
    qty: u32,
}

#[derive(Serialize, Clone)]
struct Order {
    id: u32,
    customer: String,
    items: Vec<OrderItem>,
    total_rs: u32,
}

#[derive(Deserialize)]
struct NewItem {
    name: String,
    qty: u32,
}

#[derive(Deserialize)]
struct NewOrder {
    customer: String,
    items: Vec<NewItem>,
}

struct AppState {
    orders: Mutex<Vec<Order>>,
    next_id: Mutex<u32>,
}

fn price_rs(name: &str) -> Option<u32> {
    match name {
        "White Cotton Kurta" => Some(2450),
        "Navy Blue Shalwar Kameez" => Some(3200),
        "Pastel Lawn Kurta" => Some(1950),
        _ => None,
    }
}

#[post("/orders")]
async fn create_order(
    data: web::Data<AppState>,
    body: web::Json<NewOrder>,
) -> impl Responder {
    if body.items.is_empty() {
        return HttpResponse::BadRequest().body("order needs at least one item");
    }
    let mut items = Vec::new();
    let mut total_rs = 0;
    for item in &body.items {
        match price_rs(&item.name) {
            Some(price) => {
                total_rs += price * item.qty;
                items.push(OrderItem {
                    name: item.name.clone(),
                    price_rs: price,
                    qty: item.qty,
                });
            }
            None => {
                return HttpResponse::BadRequest()
                    .body(format!("unknown product: {}", item.name));
            }
        }
    }
    let mut next_id = data.next_id.lock().unwrap();
    let order = Order {
        id: *next_id,
        customer: body.customer.clone(),
        items,
        total_rs,
    };
    *next_id += 1;
    data.orders.lock().unwrap().push(order.clone());
    HttpResponse::Created().json(order)
}

#[get("/orders")]
async fn list_orders(data: web::Data<AppState>) -> impl Responder {
    let orders = data.orders.lock().unwrap();
    HttpResponse::Ok().json(&*orders)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let state = web::Data::new(AppState {
        orders: Mutex::new(Vec::new()),
        next_id: Mutex::new(1),
    });
    println!("Actix-web shop orders API listening on http://127.0.0.1:8080");
    HttpServer::new(move || {
        App::new()
            .app_data(state.clone())
            .service(create_order)
            .service(list_orders)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

Run it:

$ cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.27s
     Running `target/debug/shop_orders`
Actix-web shop orders API listening on http://127.0.0.1:8080

The list starts empty:

$ curl -s http://127.0.0.1:8080/orders
[]

Now place an order for Ayesha: one White Cotton Kurta, two Navy Blue Shalwar Kameez, two Pastel Lawn Kurta. My first attempt sent the quantity as a string, "qty": "2", copied from a WhatsApp message where everything is text:

$ curl -s -X POST http://127.0.0.1:8080/orders \
  -H "Content-Type: application/json" \
  -d '{"customer":"Ayesha","items":[{"name":"White Cotton Kurta","qty":"2"}]}'
Json deserialize error: invalid type: string "2", expected u32 at line 1 column 68

The JSON extractor rejected the request before the handler ran, with HTTP 400. It expects a number for qty, because the struct says u32, and a string is not a number. The fix is at the data: send 2, not "2".

$ curl -s -X POST http://127.0.0.1:8080/orders \
  -H "Content-Type: application/json" \
  -d '{"customer":"Ayesha","items":[{"name":"White Cotton Kurta","qty":1},{"name":"Navy Blue Shalwar Kameez","qty":2},{"name":"Pastel Lawn Kurta","qty":2}]}'
{"id":1,"customer":"Ayesha","items":[{"name":"White Cotton Kurta","price_rs":2450,"qty":1},{"name":"Navy Blue Shalwar Kameez","price_rs":3200,"qty":2},{"name":"Pastel Lawn Kurta","price_rs":1950,"qty":2}],"total_rs":12750}

HTTP status: 201. Rs 2,450 once, plus Rs 3,200 twice, plus Rs 1,950 twice, comes to Rs 12,750. GET /orders shows the order stored:

$ curl -s http://127.0.0.1:8080/orders
[{"id":1,"customer":"Ayesha","items":[{"name":"White Cotton Kurta","price_rs":2450,"qty":1},{"name":"Navy Blue Shalwar Kameez","price_rs":3200,"qty":2},{"name":"Pastel Lawn Kurta","price_rs":1950,"qty":2}],"total_rs":12750}]

One order in, one order out, and the total was worked out by the server, not by a calculator.

Terminal output showing an Actix-web JSON error on a string quantity, then the fixed order returning total Rs 12,750 and GET /orders listing it.

Common mistakes and how to fix them

First, sending a number as a string in the JSON body, like "qty": "2". The extractor answers: "Json deserialize error: invalid type: string "2", expected u32 at line 1 column 68", with HTTP 400. The fix is a bare number, 2, because the struct field is a u32.

Second, mistyping the route, for example GET /order instead of GET /orders. The server answers with HTTP 404 and no body. Routes match exactly, so check the spelling and the plural before blaming the server.

Third, ordering a product that is not in the price list, like a Silk Sherwani. The handler answers: "unknown product: Silk Sherwani", with HTTP 400. The fix is at the data: add the product to price_rs, or correct the spelling.

Fourth, posting an order with no items at all. The handler answers: "order needs at least one item", with HTTP 400. The fix is to validate on the client too, so an empty cart never reaches the server.

Frequently Asked Questions

Is Actix-web faster than Axum? Both are fast, and published benchmarks put them close together, so speed alone rarely decides it. Pick on ergonomics: Actix-web is a complete framework with middleware included, while Axum stays closer to bare routing. The Axum Tutorial: Build a Rust API Without the Boilerplate post shows the other side.

Do I need to know async Rust to use Actix-web? The basics, yes. Handlers are async fn, you await the work, and the server runs on Tokio. One small endpoint is enough to learn the shape.

Can Actix-web serve a website, or only APIs? Both. It serves static files and templates, and this post sticks to the API side. If you come from Node, the Koa Tutorial: Build a Node.js Orders API From Scratch post builds the same kind of API in JavaScript.

Is Actix-web still maintained? Yes. Version 4 is the current line, this post ran actix-web 4.20.0, and releases continue. Check the changelog before starting a new project.

What to remember

  • Actix-web turns HTTP requests into typed Rust values through extractors, and a wrong type fails before the handler runs.
  • Keep money in whole rupees as integers, and the server works out the total the same way every time.
  • POST /orders validates each item against a price list and returns 201 with the stored order.
  • GET /orders lists every order the shop has taken.
  • Routes match exactly: /order is not /orders, and the server answers 404.

Where this leaves you

One small server, two routes, and the shop now has an order recorded once, checked against real prices, and totalled to Rs 12,750 without a calculator in sight. The JSON error was the useful part: the extractor would rather reject a bad request than let a wrong quantity reach the total. Take an order flow of your own, the kind still living in a notebook or a chat thread, and give it two routes before you give it a frontend.

Further reading

Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

Comments

Popular posts from this blog

Swift Explained: Apple's Language for iPhone, Mac, and More

LangChain Tutorial: Build Your First LLM App in Python

Ollama Tutorial: Run Your First Local LLM in Python