Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 38 ยท Getting Started

Setting Up an Axum Project with Cargo

Create a new Rust crate for Axum, choose dependencies and features, write the Tokio entry point, read configuration from the environment and run your first request.

An Axum service is an ordinary Cargo binary crate. There is no generator, no scaffolding tool and no special project layout to learn. You create a crate, add a handful of dependencies, and write a main function that builds a router and starts listening. This lesson walks through exactly that, and explains each dependency so you know why it is there.

You need a recent stable Rust toolchain (installed with rustup). Check it with rustc --version; Axum 0.8 requires a fairly new compiler, and Cargo will tell you if yours is too old. If Cargo is new to you, read Cargo and projects and crates and dependencies first.

Create the crate

Run these commands in a terminal. They are shown read-only because the in-page runner has no Cargo.

Terminal
cargo new hello-axum
cd hello-axum
cargo add axum tokio --features tokio/full
cargo add serde --features derive
cargo add serde_json tracing tracing-subscriber

The resulting Cargo.toml looks like this (exact versions will be newer when you read this):

TOML
[package]
name = "hello-axum"
version = "0.1.0"
edition = "2024"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

What each dependency does:

Crate Why you add it
axum The router, extractors and serve function.
tokio The async runtime; the full feature enables macros, networking, time and signals.
serde Serialize and Deserialize derive macros for request and response bodies.
serde_json JSON values and the json! macro.
tracing / tracing-subscriber Structured logging that Axum and Tower integrate with.

Later chapters add tower-http (CORS, tracing, compression), sqlx (databases) and others. Keep the dependency list short at first: every crate is compile time and attack surface.

The entry point

Rust's main cannot be async by itself. The #[tokio::main] attribute wraps it: it builds a Tokio runtime and runs your async body on it.

Rust
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();

    let app = Router::new().route("/", get(|| async { "up and running" }));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .expect("could not bind port 3000");
    tracing::info!("listening on {}", listener.local_addr().unwrap());

    axum::serve(listener, app).await.expect("server error");
}

Run it with cargo run, then call it from a second terminal:

Terminal
curl -i http://127.0.0.1:3000/

You should see HTTP/1.1 200 OK, a content-type: text/plain; charset=utf-8 header, a content-length header and the body. The first build downloads and compiles dependencies and can take a minute; later builds only recompile your code.

A few details worth knowing right away:

  • 127.0.0.1 versus 0.0.0.0. Binding to 127.0.0.1 accepts connections only from your own machine. Binding to 0.0.0.0 accepts them from any interface, which is what a container or server needs. Use loopback for local development.
  • bind(...).await. Binding is async in Tokio's TcpListener. It fails if the port is taken, so handle the error with a clear message.
  • axum::serve runs forever (until you add a shutdown signal, covered in your first server).

Reading configuration from the environment

Hard-coding a port is fine for a first run, but real services read settings from environment variables: the same binary then works on your laptop, in CI and in production. The standard library is enough for simple needs. This runnable example parses PORT and HOST with defaults and builds the address string you would pass to bind.

Rust Stand-in: build the bind address from environment variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In a real project you would call std::env::var("PORT") directly (or use a crate such as dotenvy to load a .env file in development), and validate once at start-up so a typo fails fast instead of at the first request.

Reading a request by hand

Axum gives you a parsed Request. Seeing how small that parsing is helps demystify it. This stand-in parses a raw request into a method, path, query string and headers, which are the same pieces you will later receive through extractors.

Rust Stand-in: parse a raw HTTP request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Helpful development tools

  • cargo check type-checks without producing a binary and is much faster than cargo build. Use it constantly.
  • cargo watch -x run (from the cargo-watch tool) restarts the server whenever a file changes.
  • RUST_LOG. With tracing-subscriber's EnvFilter, RUST_LOG=debug cargo run turns on debug logs without recompiling.
  • cargo clippy catches common mistakes; see Clippy and fmt.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do you put #[tokio::main] on main?

    The macro expands to a regular main that creates a Tokio runtime and blocks on your async function.
  2. 2. What is the difference between binding to 127.0.0.1 and 0.0.0.0?

    Loopback is reachable only from the same machine; 0.0.0.0 listens on every interface, which containers and servers need.
  3. 3. Which cargo command type-checks quickly without building a binary?

    cargo check skips code generation and is much faster than a full build.
  4. 4. Why read PORT from the environment instead of hard-coding it?

    Configuration outside the binary lets one build run locally, in CI and in production.

Summary

  • An Axum service is a normal Cargo binary: axum, tokio, serde and tracing cover most needs.
  • #[tokio::main] creates the runtime; TcpListener::bind plus axum::serve starts the server.
  • Bind to 127.0.0.1 for development and 0.0.0.0 in containers.
  • Read settings from the environment and validate them at start-up.

Next: HTTP Basics for Axum Developers