Minimal Boilerplate
Learn how Axum reduces repetitive setup code with a macro-free API, type-safe extractors, and automatic response conversion, allowing you to build a web server with very few lines.
Minimal Boilerplate
When you start building a web server in Rust, you quickly notice that many frameworks require you to write the same kind of setup code over and over again: defining route handlers with special attribute macros, manually parsing query parameters or JSON bodies, constructing HTTP responses piece by piece, and wiring everything together with verbose configuration. This repetitive setup code is called boilerplate. It doesn't add any value to your application - it just gets in the way of writing the actual logic. Axum was designed from the ground up to minimize boilerplate so that you can focus on what your application actually does.
In this page, we'll explore exactly what that means in practice. We'll start with the smallest possible Axum server and gradually add features that would normally require a lot more code in other frameworks. By the end, you'll see why Axum's "minimal boilerplate" philosophy makes it a joy to work with, especially for beginners.
What Is Boilerplate?
Before we dive into Axum's approach, let's make sure we all understand the term. Boilerplate refers to sections of code that have to be included in many places with little or no alteration. Think of it like the pre-printed text on a legal document - you have to have it, but it doesn't carry any specific meaning for your particular case. In web development, typical boilerplate includes:
- Repeating route registration patterns for every endpoint.
- Manually extracting data from the HTTP request (headers, query string, body).
- Explicitly constructing a response with the right status code and headers.
- Implementing trait methods or using macro annotations just to make a function work as a handler.
Boilerplate isn't necessarily a bad thing when it's handled by the framework. A well-designed framework hides that boilerplate behind clean abstractions so you never have to write it yourself. Axum does exactly that through a combination of type-driven design and the power of Rust's trait system.
The Smallest Axum Server
Let's start with the classic "Hello, World!" example. This is often the very first program you write when learning a new web framework, and it shows the absolute minimum amount of code needed to get a server running.
We'll build it step by step using a Stepper because the sequence matters: you need to create a project, add dependencies, write the code, and run it.
Step 1: Create a new Rust project
Open your terminal and create a new binary Rust project called hello-axum:
cargo new hello-axum
cd hello-axum
Step 2: Add the required dependencies
We need axum for the web server and tokio for the async runtime. Axum is built on top of Tokio, so we enable the full feature of Tokio to get everything we need:
cargo add axum tokio --features tokio/full
Step 3: Write the minimal server code
Replace the contents of src/main.rs with this:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Step 4: Run the server and test it
Start the server:
cargo run
In another terminal, use curl to send a request:
curl http://localhost:3000
You should see the output:
Hello, World!
Look at that code carefully. We wrote a complete HTTP server in seven lines of code (excluding imports and the async fn line, but even counting everything, it's tiny). There are no attribute macros decorating the handler. There's no manual creation of an HTTP response struct. We didn't write a single line to parse the request or set headers. The handler is just an ordinary closure that returns a string. Axum takes care of converting that string into a full HTTP response with the correct Content-Type and status code.
If you've ever written a web server using a lower-level library like Hyper directly, you know that the same functionality would require significantly more code: defining a service, implementing the Service trait, handling the request and response types, and managing asynchronous execution. Axum hides all of that behind its Router and serve function.
Boilerplate-Free Routing
One of the biggest sources of boilerplate in other frameworks is routing. Many frameworks require you to use special macros above each handler function, like this imaginary example:
#[get("/users")]
async fn list_users() { /* ... */ }
The macro generates hidden code that registers the route with the framework. While macros can reduce some typing, they also obscure what's happening and often produce confusing compiler errors. Axum takes a different approach: routing is done with plain Rust method calls on a Router. There's no magic, no code generation, and no special syntax to learn.
Consider a more realistic example with multiple routes and HTTP methods:
use axum::{routing::{get, post}, Router};
async fn root() -> &'static str {
"Home page"
}
async fn list_users() -> &'static str {
"List all users"
}
async fn create_user() -> &'static str {
"Create a new user"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(root))
.route("/users", get(list_users).post(create_user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Notice how the route method chains get(list_users).post(create_user) to handle both GET /users and POST /users in one line. There is no separate configuration object, no registration calls scattered across files, no need to name a route with a string that matches a function name. The route is just a method call that connects a path pattern to a handler. This is the essence of macro-free routing: everything is expressed with normal Rust code that the compiler can check.
This approach reduces boilerplate because you don't need to write any special annotations, and you don't need to learn a new DSL for routing. If you know how to call methods and pass function references, you can define routes.
Handlers as Ordinary Functions
In Axum, a handler is simply an async function (or closure) that returns something that can be converted into an HTTP response. The handler does not have to implement a special trait, extend a base class, or be wrapped in a struct. The function you write is the function Axum calls.
Take the previous example: async fn root() -> &'static str. That's a plain async function returning a string slice. There's no #[handler] attribute, no impl Handler for Root, no manual conversion to a Response. Axum uses Rust's trait system and type inference to understand that this function is a valid handler because &'static str implements the IntoResponse trait (we'll talk about that shortly). You can write:
async fn health_check() -> &'static str {
"OK"
}
and route it directly with .route("/health", get(health_check)). That's it. The function's signature tells Axum everything it needs to know about how to call it and how to convert its return value into an HTTP response.
This is in stark contrast to some frameworks where handlers must have a specific signature like fn(req: Request, res: Response) and you must manually write to the response. By letting handlers return values directly, Axum removes that boilerplate entirely.
Automatic Response Conversion with IntoResponse
Every handler in Axum must return something that implements the IntoResponse trait. This trait has one method, into_response(), which converts the value into an HTTP Response object. Axum provides implementations of IntoResponse for many common types, so you rarely need to write your own.
For example:
&'static strandStringbecome a200 OKresponse withContent-Type: text/plain.StatusCodebecomes a response with that status and an empty body.Json<T>(whereT: Serialize) becomes a200 OKresponse withContent-Type: application/jsonand the serialized JSON body.- Tuples like
(StatusCode, Json<T>)become a response with the given status and JSON body.
This means you can write handlers that return exactly what they mean, and Axum handles the conversion for you. You don't need to construct a Response manually, set headers, or write the body yourself. The boilerplate is gone.
Let's see a slightly more complex example that returns JSON with a custom status code:
use axum::{http::StatusCode, Json, routing::post, Router};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u64,
name: String,
}
async fn create_user() -> (StatusCode, Json<User>) {
let user = User {
id: 1,
name: "Alice".to_string(),
};
(StatusCode::CREATED, Json(user))
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", post(create_user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here, the handler returns a tuple (StatusCode, Json<User>). Axum knows that StatusCode and Json<T> both implement IntoResponse, and it combines them into a single response with status 201 Created and a JSON body. We didn't have to call .status(201) or .json(&user) manually. The return type communicates the intent, and Axum does the rest.
This is a huge reduction in boilerplate compared to manually building a response object.
Type-Driven Extractors Remove Manual Parsing
Another area where boilerplate creeps in is extracting data from the incoming request. In many frameworks, you must manually access the request object, read query parameters from the URL string, parse them into the right types, and handle errors. That can easily add ten or more lines of code per handler.
Axum uses extractors - types that implement FromRequest or FromRequestParts. Instead of manually parsing, you declare the extractor as a parameter to your handler. Axum automatically runs the extractor, parses the data, and passes it to you. If parsing fails, Axum returns an appropriate error response (like 400 Bad Request) without you writing any error-handling code.
Let's look at a handler that extracts a path parameter:
use axum::{extract::Path, routing::get, Router};
async fn get_user(Path(user_id): Path<u32>) -> String {
format!("User ID: {}", user_id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{id}", get(get_user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
If you send a request to /users/42, the handler receives 42 as a u32. If you send /users/abc, Axum automatically returns a 400 Bad Request because abc cannot be parsed as a u32. You didn't write a single line of parsing or error handling. That's minimal boilerplate in action.
The same idea applies to query strings, JSON bodies, headers, and more. For example, a handler that parses a JSON body looks like this:
use axum::{Json, routing::post, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
async fn create_user(Json(payload): Json<CreateUser>) -> String {
format!("Created user {} with email {}", payload.name, payload.email)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", post(create_user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
The Json<CreateUser> parameter tells Axum to read the request body, parse it as JSON, and deserialize it into a CreateUser struct. If the body is missing or invalid, Axum returns a 400 Bad Request or 422 Unprocessable Entity automatically. Without extractors, you would have to read the entire body, call serde_json::from_slice, handle the error, and only then proceed to your logic.
JSON bodies have a default size limit:
Json, String, Bytes, and Form bodies are capped at 2 MB by default (DefaultBodyLimit). A larger body is rejected with 413 Payload Too Large before your handler runs. Raise it with DefaultBodyLimit::max(10 * 1024 * 1024) (applied as a layer) or remove it entirely with DefaultBodyLimit::disable() - but only after thinking about how much memory an attacker could make your server allocate.
Extractors are the primary reason Axum handlers can stay so small. They encapsulate the repetitive work of parsing and validation, leaving only the essential application logic.
State Sharing Without Verbose Wiring
Almost every real application needs to share some state between handlers, such as a database connection pool or a configuration object. In many frameworks, you have to manually pass that state around, store it in global variables, or use dependency injection containers. Axum's State extractor makes it trivial.
First, define your application state as a Rust struct. Then, attach it to the router using .with_state(...). Any handler that needs access to that state simply adds a State<MyState> parameter. Axum injects the state automatically.
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
app_name: String,
}
async fn get_name(State(state): State<AppState>) -> String {
format!("Welcome to {}", state.app_name)
}
#[tokio::main]
async fn main() {
let state = AppState {
app_name: "My Axum App".to_string(),
};
let app = Router::new()
.route("/", get(get_name))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Notice that we didn't need Arc here because AppState derives Clone. If your state contains non-cloneable fields or you want to avoid deep copies, you can wrap it in Arc. The point is, the setup is minimal: define the struct, call .with_state, and add State<...> to the handler signature. No manual passing, no global variables, no complex dependency injection setup.
This is a perfect example of how Axum turns what could be many lines of boilerplate into a single type annotation.
Comparing Axum to Raw Hyper
To truly appreciate how much boilerplate Axum eliminates, it helps to see what the same functionality would look like using a lower-level HTTP library like Hyper directly. Hyper is the HTTP engine that Axum is built on, so this isn't a comparison of two entirely different worlds - it shows the abstraction Axum provides.
This is for understanding, not a practical suggestion:
You would almost never write a web server with raw Hyper today if you can use Axum. The comparison is purely to illustrate the concept of boilerplate reduction.
Here is a minimal "Hello, World!" server using only Hyper and Tokio (without Axum). This code is adapted from Hyper's official examples and is accurate for Hyper 1.x. It needs these dependencies:
[dependencies]
hyper = { version = "1.12.0", features = ["server", "http1"] }
hyper-util = { version = "0.1", features = ["tokio"] }
tokio = { version = "1.54.1", features = ["full"] }
use std::convert::Infallible;
use hyper::{body::Incoming, service::service_fn, Request, Response};
use hyper_util::rt::TokioIo;
use tokio::net::TcpListener;
async fn handle_request(_req: Request<Incoming>) -> Result<Response<String>, Infallible> {
Ok(Response::new("Hello, World!".to_string()))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("0.0.0.0:3000").await?;
loop {
let (stream, _) = listener.accept().await?;
let io = TokioIo::new(stream);
tokio::task::spawn(async move {
let service = service_fn(handle_request);
if let Err(err) = hyper::server::conn::http1::Builder::new()
.serve_connection(io, service)
.await
{
eprintln!("Error serving connection: {:?}", err);
}
});
}
}
Even for this single route, we have to manually:
- Define a service function that takes a
Request<Incoming>and returns aResponse<String>. - Implement error handling with
Infallible(a type that means "no error"). - Accept incoming TCP connections in a loop.
- Wrap each connection in
TokioIoto bridge Tokio and Hyper. - Spawn a new task for each connection.
- Build an HTTP/1.1 server using
hyper::server::conn::http1::Builder. - Call
serve_connectionwith the service and handle any connection errors.
That's roughly 20 lines of setup code for one route that returns a static string. Axum does the same thing in 7 lines, and those 7 lines are much easier to understand. The difference is even more dramatic when you add routing, parsing, state, or JSON.
Graceful shutdown is opt-in, in both:
Neither the raw Hyper example above nor axum::serve shuts down gracefully by default - Ctrl+C just kills the process mid-request. In Axum, graceful shutdown is one method call: .with_graceful_shutdown(...) on the Serve future returned by axum::serve, passing a future that completes when it is time to stop (for example, one that awaits tokio::signal::ctrl_c()). Axum then stops accepting new connections and waits for in-flight requests to finish before the process exits.
Don't confuse minimal code with limited capability:
Axum is not a toy framework; it's a thin but powerful layer over Hyper. The boilerplate it removes is exactly the repetitive plumbing, not the features. You still have full access to the underlying HTTP details when you need them.
Common Mistakes That Add Unnecessary Boilerplate
Even though Axum is designed to minimize boilerplate, beginners sometimes write code that accidentally reintroduces it. Here are the most common pitfalls and how to avoid them.
Mistake 1: Manually building responses
Instead of returning simple types and letting IntoResponse handle the conversion, beginners sometimes construct a full Response object by hand:
use axum::{body::Body, http::Response, routing::get, Router};
async fn handler() -> Response<Body> {
Response::builder()
.status(200)
.header("content-type", "text/plain")
.body(Body::from("Hello"))
.unwrap()
}
This is unnecessary because &'static str already implements IntoResponse. Just return "Hello" and Axum will set the correct status and content type for you.
Manually building responses is error-prone:
You might forget to set the correct Content-Type or status code, leading to subtle bugs. Let Axum handle it unless you have a specific reason to customize.
Mistake 2: Parsing query parameters or path segments manually
Instead of using extractors, some developers try to parse query strings themselves:
use axum::{extract::RawQuery, routing::get, Router};
async fn handler(RawQuery(query): RawQuery) -> String {
// `RawQuery` wraps an `Option<String>` - it is `None` when the URL
// has no `?` query string at all, so unwrap it before splitting.
let query = query.as_deref().unwrap_or("");
let params: Vec<&str> = query.split('&').collect();
// ... manual parsing ...
}
This is tedious and error-prone. Use the Query extractor with a struct that derives Deserialize:
use axum::{extract::Query, routing::get, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct Params {
page: u32,
}
async fn handler(Query(params): Query<Params>) -> String {
format!("Page: {}", params.page)
}
Using RawQuery loses type safety:
Manual parsing means you have to handle invalid numbers, missing fields, and encoding issues yourself. The Query extractor does all of that automatically and returns a proper error response.
Mistake 3: Implementing custom response types when a tuple would do
Sometimes you need to return a status code along with a body. Beginners might create a custom struct that implements IntoResponse manually, but Axum already supports tuples of IntoResponse types. So (StatusCode, Json<T>) works out of the box. There's no need to write a custom implementation unless you want to encapsulate more complex logic or reuse a common response shape.
Mistake 4: Using Extension for state instead of State
Axum provides two ways to share state: State and Extension. State is checked at compile time - if a handler asks for a state type that wasn't provided, the code won't compile. Extension is more dynamic and fails at runtime with a 500 Internal Server Error if the extension is missing. For most cases, State is simpler and safer, with less boilerplate because you don't need to wrap your state in an Extension layer. Prefer State unless you have a specific reason to use extensions.
Thinking About Minimal Boilerplate as a Design Philosophy
When you're new to Axum, it's helpful to think of the framework as a concierge that handles the mundane details of HTTP for you. You write the interesting part - the logic that makes your application unique - and Axum handles the plumbing: parsing requests, converting responses, registering routes, and managing errors. The less time you spend on plumbing, the more you can focus on what your application actually does.
This philosophy extends beyond just the code you write. It also affects how you structure your application. Because handlers are just functions with typed parameters, you can compose them, test them in isolation, and reason about them without worrying about the HTTP layer. You can write a handler as a pure function that takes some inputs and returns some outputs, and then let Axum adapt it to the web.
As you continue learning Axum, you'll discover even more ways the framework reduces boilerplate: middleware from the Tower ecosystem that you can add with a single .layer() call, automatic JSON serialization with serde, and error handling that converts errors into responses with minimal code. Each of these builds on the same idea: let the framework do the boring work.
You're on the right track:
If you find yourself writing very little HTTP-specific code and mostly application logic, you're using Axum exactly as intended. That's the sign of minimal boilerplate working for you.
Summary
The concept of "minimal boilerplate" in Axum is not just a marketing slogan - it's a direct result of several design decisions that work together:
- Macro-free routing means you use plain method calls instead of special annotations.
- Ordinary functions as handlers mean you don't implement traits or wrap code in structs.
IntoResponseconverts your return values into HTTP responses automatically.- Extractors parse request data so you don't write manual parsing code.
Stateshares application data without verbose wiring.
Taken together, these features allow you to build a fully functional web server in a handful of lines while retaining full control when you need it. As you explore other parts of Axum - like routing, handlers, extractors, and responses - you'll see this philosophy repeatedly: each abstraction exists to remove friction, not to hide power. But for now, take a moment to appreciate how much you can accomplish with just a few lines of clear Rust code.