Rust Web Development Actix web & Axum Tutorial

Zaheer Ahmad 5 min read min read
Python
Rust Web Development Actix web & Axum Tutorial

Introduction

Rust web development has become one of the fastest-growing areas in modern backend engineering. In this Rust Web Development: Actix-web & Axum Tutorial, we will explore two powerful frameworks: Actix-web and Axum, which are widely used to build fast, secure, and scalable web applications.

For Pakistani students in cities like Lahore, Karachi, and Islamabad, learning Rust web frameworks can open doors to high-paying remote jobs, freelancing opportunities, and internships in global tech companies. Unlike traditional languages, Rust focuses on memory safety and performance without a garbage collector, making it ideal for backend systems, APIs, and microservices.

Actix-web is known for its speed and maturity, while Axum is modern, ergonomic, and built on top of the Tokio ecosystem. Together, they represent the best of Rust web development.

By the end of this tutorial, you will understand:

  • How Rust web frameworks work internally
  • How to build APIs using Actix-web and Axum
  • Real-world backend examples
  • Common mistakes and best practices

Prerequisites

Before starting this tutorial, you should have:

  • Basic understanding of Rust programming language
  • Familiarity with functions, structs, and ownership
  • Basic knowledge of HTTP (GET, POST, REST APIs)
  • Rust installed (rustup setup)
  • A code editor like VS Code

Optional but helpful:

  • Understanding of async programming (async/await)
  • Basic JSON handling

If you are new, consider reading Rust Tutorial on theiqra.edu.pk first.


Core Concepts & Explanation

Understanding Rust Async Runtime

Rust web frameworks rely heavily on asynchronous programming. Instead of blocking threads, Rust uses async/await to handle multiple requests efficiently.

Example concept:

  • Traditional server: one request = one thread
  • Rust async server: thousands of requests = few threads

This is why frameworks like Actix-web and Axum are extremely fast.


Actix-web Architecture

Actix-web is built on the Actix actor system. It uses:

  • App → Application container
  • Handlers → Functions that process requests
  • Extractors → Extract data from requests
  • Middleware → Logging, authentication, etc.

Example idea:

  • Request comes in → middleware processes → handler executes → response returned

Axum Architecture

Axum is a modern Rust web framework built on Tokio and Hyper.

Key components:

  • Router → Defines routes
  • Handlers → Async functions
  • Extractors → Query, JSON, Path
  • Layers → Middleware system

Axum is designed for simplicity and composability.


Practical Code Examples

Example 1: Actix-web REST API (Simple Server)

use actix_web::{get, App, HttpServer, Responder};

#[get("/")]
async fn hello() -> impl Responder {
    "Hello from Actix-web!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(hello)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

Line-by-line Explanation

  • use actix_web... → Imports required Actix-web components
  • #[get("/")] → Defines HTTP GET route for /
  • async fn hello() → Async handler function
  • "Hello from Actix-web!" → Response returned to client
  • #[actix_web::main] → Starts async runtime
  • HttpServer::new() → Creates server instance
  • App::new().service(hello) → Registers route handler
  • .bind("127.0.0.1:8080") → Sets server address
  • .run().await → Runs server asynchronously

Example 2: Axum Real-World API (Todo List)

use axum::{
    routing::get,
    Router,
    Json,
};
use serde::Serialize;

#[derive(Serialize)]
struct Todo {
    id: u32,
    task: String,
}

async fn get_todos() -> Json<Vec<Todo>> {
    Json(vec![
        Todo {
            id: 1,
            task: "Learn Rust in Lahore".to_string(),
        },
        Todo {
            id: 2,
            task: "Build Axum API in Karachi".to_string(),
        },
    ])
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/todos", get(get_todos));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();

    axum::serve(listener, app).await.unwrap();
}

Line-by-line Explanation

  • use axum... → Imports Axum components
  • #[derive(Serialize)] → Enables JSON conversion
  • struct Todo → Defines data model
  • async fn get_todos() → API handler function
  • Json(vec![...]) → Returns JSON response
  • Router::new() → Creates application router
  • .route("/todos", get(get_todos)) → Defines endpoint
  • TcpListener::bind() → Opens server port
  • axum::serve() → Starts server

Common Mistakes & How to Avoid Them

Mistake 1: Blocking Code in Async Handlers

Problem

Using blocking operations like file I/O inside async functions slows down the server.

Example bad code:

std::thread::sleep(std::time::Duration::from_secs(2));

Fix

Use async alternatives:

tokio::time::sleep(std::time::Duration::from_secs(2)).await;

Mistake 2: Incorrect Route Registration

Problem

Handlers not registered properly in App/Router.

Fix

Always ensure:

  • Actix-web → .service(handler)
  • Axum → .route("/path", get(handler))

Practice Exercises

Exercise 1: Build a Simple Greeting API

Problem

Create an Actix-web server that returns:

  • /hello → "Hello Pakistan"

Solution

#[get("/hello")]
async fn greet() -> impl Responder {
    "Hello Pakistan"
}

Explanation:

  • Defines /hello route
  • Returns static string response

Exercise 2: Extend Todo API

Problem

Add a new endpoint /todo/1 that returns a single task.

Solution

async fn get_todo() -> Json<Todo> {
    Json(Todo {
        id: 1,
        task: "Study Axum in Islamabad".to_string(),
    })
}

Explanation:

  • Returns single JSON object
  • Uses Axum JSON extractor

Frequently Asked Questions

What is Actix-web used for?

Actix-web is a high-performance Rust web framework used for building APIs, microservices, and backend systems. It is widely used in production due to its speed and stability.


What is Axum in Rust?

Axum is a modern Rust web framework built on Tokio. It focuses on simplicity, type safety, and modular design, making it ideal for scalable web applications.


Which is better: Actix-web or Axum?

Actix-web is faster and more mature, while Axum is easier to use and more modern. Beginners often prefer Axum, while large-scale systems often use Actix-web.


How do I choose a Rust web framework?

If you want performance → choose Actix-web. If you want simplicity and modern design → choose Axum. Both are excellent choices for backend development.


Can I get a job after learning Rust web frameworks?

Yes. Many companies hire Rust developers for backend roles, especially in systems programming, fintech, and cloud infrastructure. Pakistani students can also find remote freelancing opportunities.


Summary & Key Takeaways

  • Rust web frameworks are fast, safe, and modern
  • Actix-web is powerful and production-ready
  • Axum is simple and developer-friendly
  • Async programming is essential in Rust web development
  • Both frameworks are excellent for APIs and microservices
  • Learning Rust improves freelancing and job opportunities globally

Now that you understand Rust web development, continue learning with:


This Actix-web tutorial and Axum tutorial Rust guide gives you a strong foundation in modern backend development. Keep practicing by building small APIs and gradually move toward full production-grade systems.

Practice the code examples from this tutorial
Open Compiler
Share this tutorial:

Test Your Python Knowledge!

Finished reading? Take a quick quiz to see how much you've learned from this tutorial.

Start Python Quiz

About Zaheer Ahmad