Learn Axum Β· 1/13

Welcome to Axum & Ecosystem Setup

7 min read

Course: Axum

Topic: Welcome to Axum & Ecosystem Setup


πŸ‘‹ Welcome, Rustacean!

Welcome to the backend engineering equivalent of entering a finely tuned German automobile factory. You have chosen Axum.

You are probably here because you heard Rust is fast (it is), safe (it mostly is, unless you fight the borrow checker), and that Axum is the new "cool kid" on the block. Today, we aren't just writing code; we are building a mental model of how a modern, asynchronous web server breathes.

Let's get your hands dirty. πŸ› οΈ


1. The "Why": Axum vs. Actix vs. Rocket πŸ₯Š

The Problem:
Rust has a "fragmented" web ecosystem. In languages like Go (Gin/Echo) or Node (Express), choices are often straightforward. In Rust, you have three titans: Actix-web, Rocket, and Axum. This causes "Analysis Paralysis"β€”spending 3 weeks deciding which framework to use instead of building the app.

The Solution:
Let's break them down based on industry usage.

Framework The Vibe The Tech Industry Verdict
Rocket πŸš€ "It just works." Heavy use of Macros. Feels like Magic. Great for prototyping. Historically struggled with async stability (fixed now), but compilation times can be slower due to macro expansion.
Actix-web 🎭 "I am Speed." Uses the Actor Model. Independent ecosystem. Consistently tops benchmarks. However, the API can feel distinct from the rest of the standard Rust async ecosystem.
Axum βš“ "I am the Standard." Built on top of Hyper and Tokio. The winner for general use. It doesn't try to hide how HTTP works. If you know how Tokio works, you know Axum.

Why Axum wins for us:
Axum is developed by the same people who maintain Tokio (the runtime used by 90% of Rust async apps). This means:

  1. Interoperability: Middleware written for other frameworks (via the Tower crate) works in Axum out of the box.
  2. No Magic: It uses standard Rust traits rather than complex macros.
  3. Ergonomics: It leverages Rust's type system to extract data from requests automatically (Extractors).

Fun Fact: Actix-web was once so fast that people accused it of "cheating" in benchmarks by using unsafe code. It has since matured, but Axum is the "safe default" right now.


2. The Foundation: Understanding Tokio and Hyper Conceptually πŸ—οΈ

Before we install anything, we need to learn the alphabets. You cannot run Axum without Tokio and Hyper.

The Problem:
Rust, the language, does not have a built-in background runtime. If you write an asynchronous function (async fn), Rust compiles it into a state machine but has no idea how to actually run it. It's like having a car engine blueprint but no mechanic to assemble and start it.

The Solution:

A. Tokio (The Runtime) ⏱️

Definition: Tokio is an event-driven, non-blocking I/O platform for writing asynchronous applications.
Function: It creates a thread pool (workers) and polls your tasks. When your code waits for a database or a network request, Tokio pauses that task and runs a different one on the same thread.

  • Analogy: Imagine a waiter (Thread) at a busy restaurant. The waiter takes an order and sends it to the kitchen (I/O). While the kitchen cooks, the waiter doesn't stand there staring at the stove; they go serve another table. Tokio is the manager telling the waiter where to go.

B. Hyper (The Protocol) 🌐

Definition: Hyper is a fast, safe, and correct HTTP implementation for Rust.
Function: It handles the raw bytes of TCP streams, parsing "GET / HTTP/1.1" into data structures your code can understand.

  • Analogy: If Tokio is the engine, Hyper is the wheels. It translates the engine's power into movement on the road (the Internet).

C. Axum (The Framework) πŸŽ›οΈ

Definition: Axum is a high-level wrapper around Hyper.
Function: Hyper is too low-level for daily use (you don't want to parse byte streams manually). Axum provides Routing (mapping /users to a function) and Extractors (turning JSON into Structs).

Relationship:

User Request -> Tokio (Accepts connection) -> Hyper (Parses HTTP) -> Axum (Routes to your handler).


3. Project Setup: Cargo, Dependencies, and "Hello, Axum!" πŸ“¦

Let's build. We are using Axum 0.7+ (the latest standard).

Step 1: Create the Project
Open your terminal. Do not fear the black box.

bash
cargo new axum-intro
cd axum-intro

Step 2: The Dependencies (Cargo.toml)
The Problem: We need the framework (axum), the runtime (tokio), and serialization support (serde - because nobody writes raw JSON strings manually).

The Solution:
Run these commands to add dependencies (this ensures you get the latest compatible versions):

bash
cargo add axum
cargo add tokio --features full
cargo add serde --features derive

Check your Cargo.toml. It should look similar to this:

toml
[dependencies]
axum = "0.8" # Or 0.7, depending on the day you read this. 
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }

Note on tokio features = ["full"]: By default, Tokio is minimal. We need the "full" feature set to get the macros (#[tokio::main]) and the multi-threaded runtime.


4. The Server: Binding TCP Listeners and Serving the App πŸ–₯️

Now, we write the main.rs.

The Problem:
An application is just a file on a disk. To make it a server, it must ask the Operating System for permission to "listen" on a specific port (like port 3000) for incoming signals.

The Solution:
We will use tokio::net::TcpListener to bind to a port, and axum::serve to handle the traffic.

The Code (src/main.rs):

rust
use axum::{
    response::Html,
    routing::get,
    Router,
};
use std::net::SocketAddr;

// 1. The Entry Point
// Rust's main function is synchronous by default. 
// This macro transforms it into an async runtime wrapper.
#[tokio::main]
async fn main() {
    // 2. The Router
    // This defines: "If a user goes to '/', run the 'handler' function."
    let app = Router::new()
        .route("/", get(handler));

    // 3. The Address
    // We bind to 127.0.0.1 (localhost) on port 3000.
    // 0.0.0.0 is used for Docker/Production usually.
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    
    println!("πŸš€ Server started successfully!");
    println!("πŸ”— Listening on http://{}", addr);

    // 4. The Listener (The TCP Binding)
    // We use Tokio's async TCP listener.
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();

    // 5. The Server (The loop)
    // axum::serve takes the listener and the app (router)
    // and loops infinitely, handling requests.
    axum::serve(listener, app)
        .await
        .unwrap();
}

// 6. The Handler
// A simple async function that returns HTML.
async fn handler() -> Html<&'static str> {
    Html("<h1>Hello, Axum! πŸ¦€</h1>")
}

Detailed Breakdown of What Just Happened:

  1. #[tokio::main]: This is a macro. It quietly replaces your main function with code that starts the Tokio runtime. Without this, you cannot use .await.
  2. Router::new(): The map of your application.
  3. TcpListener::bind: This is the most critical step. It tells the OS "Reserve port 3000 for me." If you try to run this twice, the second one will crash because the port is occupied (Address in use error).
  4. axum::serve: This function effectively says, "For every new connection on this listener, spawn a Tokio task to handle it using the rules defined in app."

Run it:

bash
cargo run

Wait for it... Rust compilers take their time. Use this time to hydrate. πŸ’§

Verify:
Open your browser and go to http://127.0.0.1:3000.
You should see a bold Hello, Axum!


🧠 Practical Industry Tip: The "0.0.0.0" Trap

In the example above, we used 127.0.0.1.

  • 127.0.0.1 (Localhost): Only your computer can access the server. Safe for development.
  • 0.0.0.0 (All Interfaces): Anyone on the network can access it.

Industry Standard: When deploying to Docker or AWS, you must bind to 0.0.0.0. If you bind to 127.0.0.1 inside a Docker container, the outside world (your browser) cannot connect to it, because localhost inside the container is not localhost of your laptop!

To make your code production-ready, you would eventually read the port and address from Environment Variables, but that's a lesson for another day.


πŸ“š References & Further Reading

Next Topic: We will look into Routing and Extractorsβ€”how to actually read data sent by users without pulling your hair out. Stay tuned! πŸš€

Challenge

Your task is to implement a sequence of asynchronous operations using JavaScript Promises to fetch and process user data.

  1. Create a function named fetchUserData that returns a Promise. This promise should simulate a network request by resolving after a 1000ms delay with a user object: { id: 1, name: 'John Doe' }.

  2. Create a function named fetchUserPosts that accepts a userId as an argument and returns a Promise.

    • If the userId is a number, the promise should resolve after a 1500ms delay with an array of posts: [{ postId: 101, title: 'Post 1' }, { postId: 102, title: 'Post 2' }].
    • If the userId is not a number, the promise should immediately reject with an error message: 'Invalid user ID'.
  3. Create a function named processData that orchestrates the data fetching.

    • This function should first call fetchUserData.
    • Then, using the id from the resolved user data, it should call fetchUserPosts.
    • The final result of the promise chain should be a new object containing the user's name and their posts, formatted as: { name: 'John Doe', posts: [...] }.
    • Implement error handling using a .catch() block to log any errors that might occur during this process.

Expected result

The final code should correctly implement three functions:

  1. fetchUserData: This function must return a Promise that resolves with the object { id: 1, name: 'John Doe' } after a 1000ms timeout.

  2. fetchUserPosts: This function must accept a userId and return a Promise. The promise should use a 1500ms timeout to resolve with [{ postId: 101, title: 'Post 1' }, { postId: 102, title: 'Post 2' }] if the userId is a number. It must reject with the string 'Invalid user ID' if the userId is not a number.

  3. processData: This function must correctly chain the two promises above.

    • It calls fetchUserData first.
    • It uses .then() to get the user object and passes the user.id to fetchUserPosts.
    • A subsequent .then() block should process the results to create and return (or log) a final object in the format { name: 'John Doe', posts: [...] }.
    • A .catch() block must be chained at the end to handle any potential rejections from either promise, logging the error to the console.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.