Hello, Axum! & Project Setup
1. Welcome and Icebreaker:
Welcome to your Axum journey! Let’s start with a fun question: What’s the most interesting web API you’ve ever used or built?
2. Outline the Session:
Agenda:
- Concept Explanation: What is Axum? Why use it?
- Live Coding: Setting up your first Axum project and writing a “Hello, Axum!” server.
- Tasks: Practice by customizing your handler.
Learning Outcomes:
- Understand what Axum is and its core purpose.
- Set up a new Axum project from scratch.
- Write and run a basic Axum HTTP server.
Expectations: Ask questions and try the code yourself!
3. Concept Explanation:
Axum is a web framework for Rust, designed for building fast and reliable web APIs. It is built on top of the powerful tower and hyper libraries, focusing on type safety, modularity, and async-first design. Axum makes it easy to define routes, handlers, and extract data from requests using Rust’s strong type system.
Key concepts:
- Router: Defines how requests are routed to handlers.
- Handler: An async function that processes a request and returns a response.
- Tokio: The async runtime that powers Axum.
4. Live Coding Demonstration:
Let’s set up a new Axum project and create a simple server.
Step 1: Create a new project
cargo new my_axum_api --bin
cd my_axum_api
Step 2: Add dependencies
Edit your Cargo.toml:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
Step 3: Write your first Axum app
Edit src/main.rs:
use axum::{Router, routing::get};
async fn root() -> &'static str {
"Hello, Axum!"
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(root));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
println!("Listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
}
Step 4: Run the server
cargo run
Visit http://localhost:3000 and you should see “Hello, Axum!”.
Best Practices:
- Use async functions for handlers.
- Keep dependencies up to date.
- Use clear route paths.
Common Pitfalls:
- Forgetting to use
#[tokio::main]for async main. - Not adding required dependencies in
Cargo.toml.
5. Tasks
Your Turn:
- Change the root handler to return your name instead of “Hello, Axum!”.
- Add a new route
/greetthat returns “Welcome to Axum!”. - Try changing the port number and see what happens.