Hello, World!
Let’s start with the simplest possible Axum application.1
Create the project
If you haven’t already, create a new Rust project and add dependencies:Update
Cargo.toml:2
Write the server code
Replace the contents of
src/main.rs with this code:3
Run the server
Start your server:You should see:
4
Test the endpoint
The
#[tokio::main] macro sets up the async runtime. All Axum handlers are async functions.Understanding the code
Let’s break down what’s happening:Router
Router is the core of your application. You add routes using the .route() method, specifying:
- The path (
"/") - The HTTP method (
get) - The handler function (
handler)
Handler
IntoResponse. The Html type tells Axum to set the Content-Type header to text/html.
Server
Multiple routes
Let’s add more routes to handle different paths and HTTP methods:Testing the JSON endpoint
Test the POST endpoint with curl:Working with extractors
Axum provides extractors to parse different parts of requests:Response types
Handlers can return different response types:Adding middleware
Use Tower middleware to add cross-cutting concerns:Add
tower-http = { version = "0.6", features = ["trace"] } to use TraceLayer.What’s next?
You now have a working Axum application! Here are some next steps:Routing
Learn about advanced routing patterns and path parameters
Extractors
Deep dive into request extractors and validation
State management
Share application state across handlers
Middleware
Add authentication, logging, and other cross-cutting concerns