What a Web Framework Provides
Understand the core responsibilities of a web framework like Axum and how it simplifies building web servers.
What a Web Framework Provides
A web framework is a library that gives you a structured way to build web applications. Instead of manually handling every detail of HTTP - parsing raw requests, routing by hand, and crafting response strings - a framework provides ready-made tools for the common, repetitive parts. That lets you focus on the unique logic of your application: what happens when someone creates an account, fetches a list of products, or posts a comment.
In Axum's case, the framework is built for the Rust language. It sits on top of Tokio (an async runtime) and Hyper (an HTTP library), and it gives you a clean, type-safe way to define routes, extract data from requests, produce responses, and run middleware. This page explains the general jobs a web framework does, using Axum as the concrete example so you can see each concept in action.
The Problem a Web Framework Solves
Imagine you decided to build a web server from scratch, using only a networking library that gives you raw TCP connections. A client (like a browser) sends an HTTP request, which is just a block of text. To handle it, you would need to:
- Read the raw bytes from the socket.
- Parse the first line to figure out the method (GET, POST, etc.) and the path.
- Parse all the headers.
- Read the body if there is one.
- Decide, based on the path and method, which piece of your application code should run.
- Call that code and get a result.
- Convert that result into a properly formatted HTTP response (status line, headers, body).
- Write the response back to the socket.
All of that is plumbing - it has nothing to do with your actual business logic, like looking up a user or saving a record. If you write this by hand for every project, you'll spend days on boilerplate and repeat the same low-level code over and over. A web framework extracts that plumbing into reusable components, so you can write something like:
async fn get_user() -> String {
// Your application logic here
"Here is the user".to_string()
}
The framework handles the raw socket, the HTTP parsing, the routing decision, and the response formatting. You only write the interesting part.
What about HTTP libraries?:
A library like Hyper can parse HTTP for you, but it does not give you routing, extractors, or middleware. It's a lower-level building block. A framework adds structure and convenience on top.
Core Components of a Web Framework
Every full-featured web framework, Axum included, provides four main capabilities:
- Routing - deciding which handler function should run for a given URL and HTTP method.
- Request parsing - extracting typed data from the request (path segments, query strings, headers, body) so your handler doesn't have to do string munging.
- Response generation - converting whatever your handler returns into a valid HTTP response with status code and headers.
- Middleware - code that runs before or after the handler, for cross-cutting concerns like logging, authentication, compression, and timeouts.
Some frameworks also bundle error handling and state management as first-class features. Axum does both: it has a predictable error model and several ways to share application state with handlers. We'll touch on those later in this page.
Routing - Mapping URLs to Code
Routing is the mechanism that takes an incoming request's method and path and finds the correct handler. Without routing, you'd write a giant match statement that checks every possible path - ugly, error-prone, and hard to maintain.
In Axum, you build a Router and attach routes to it. A route pairs an HTTP method (like GET or POST) with a path pattern and a handler function. Here is the smallest possible example:
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();
}
This code creates an app that responds to GET / with the text Hello, world!. The get() function wraps the handler closure and tells Axum to only match the GET method. The Router::new().route(...) call registers that mapping. When a request comes in, Axum looks at the path and method, finds the matching route, and calls the handler.
You can register multiple routes for different paths and methods:
use axum::{routing::{get, post}, Router};
async fn root() -> &'static str {
"Welcome to the homepage"
}
async fn create_user() -> &'static str {
"Creating a user"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(root))
.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, a GET request to / runs root, while a POST request to /users runs create_user. If someone sends GET /users, Axum returns a 405 Method Not Allowed - the path /users exists, but no GET handler is registered for it. A 404 Not Found is only for paths that match no route at all. That distinction is a huge convenience: the framework automatically rejects method mismatches with the right status code.
Axum also supports path parameters, like /users/{id}, which we'll see in the request parsing section. The key idea: routing turns a messy URL string into a clean function call.
You can customize the 405 response:
When a path matches but the method does not, Axum's default 405 Method Not Allowed response has an empty body and an Allow header listing the methods that path does support. If you want a custom response for that case - for example, a JSON error - set it with Router::method_not_allowed_fallback, which takes a service that runs whenever a request hits a known path with an unknown method.
Request Parsing - Extractors
Handlers often need data from the incoming request: a user ID from the URL, a search term from query parameters, JSON from the body, or a specific header. A framework lets you declare what you need as function arguments, and it fills them in for you. In Axum, these declarative arguments are called extractors.
An extractor is a type that knows how to pull a piece of information out of the request. For example:
use axum::{
extract::{Path, Query, Json},
routing::get,
Router,
};
use std::collections::HashMap;
async fn get_user(Path(user_id): Path<u32>) -> String {
format!("User ID: {}", user_id)
}
async fn search(Query(params): Query<HashMap<String, String>>) -> String {
format!("Search params: {:?}", params)
}
async fn create_item(Json(payload): Json<serde_json::Value>) -> String {
format!("Received JSON: {}", payload)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}", get(get_user))
.route("/search", get(search))
.route("/items", axum::routing::post(create_item));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
In this example:
Path<u32>extracts the{user_id}segment from the URL and parses it as an unsigned 32-bit integer. If the path contains something that isn't a number (e.g./users/abc), Axum automatically returns a400 Bad Requestwithout you writing any error code.Query<HashMap<String, String>>takes all query parameters (like?name=alice&age=30) and turns them into a map.Json<serde_json::Value>reads the request body, parses it as JSON, and gives you the parsed value. If the body isn't valid JSON, Axum returns400 Bad Request.
The beauty is that your handler signature declares what it needs, and the framework does the extraction, validation, and error handling. You never touch raw strings or bytes unless you want to.
Extractor order matters:
Extractors that consume the request body (like Json, String, or Bytes) must be the last argument in your handler. If you put another extractor after them, the code will not compile. This is because once the body is read, it can't be read again. Axum enforces this at compile time.
Forgetting to add a route's extractor:
If you define a handler that expects a Path<u32> but forget to include {user_id} in the route pattern, Axum will return a runtime error (usually a 500 Internal Server Error). The mismatch between the route definition and the handler's expected extractors is a common beginner mistake. Always double-check that your path parameters match.
Response Generation
Your handler can return many different types, and Axum will convert each into a proper HTTP response. This conversion is defined by a trait called IntoResponse. The simplest return type is a string - Axum turns it into a 200 OK response with Content-Type: text/plain.
You can return more complex responses by using tuple types or specific response types. For example:
use axum::{
body::Body,
http::StatusCode,
response::{Json, Html},
routing::get,
Router,
};
use serde_json::{json, Value};
async fn plain_text() -> &'static str {
"Hello, plain text!"
}
async fn json_response() -> Json<Value> {
Json(json!({ "message": "Hello, JSON!" }))
}
async fn html_response() -> Html<&'static str> {
Html("<h1>Hello, HTML!</h1>")
}
async fn custom_status() -> (StatusCode, &'static str) {
(StatusCode::CREATED, "Resource created")
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/text", get(plain_text))
.route("/json", get(json_response))
.route("/html", get(html_response))
.route("/create", axum::routing::post(custom_status));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here:
plain_textreturns a&'static str, which becomes a200 OKtext response.json_responsereturnsJson<Value>, which Axum serializes to JSON and setsContent-Type: application/json.html_responsereturnsHtml<&'static str>, setting the content type totext/html.custom_statusreturns a tuple(StatusCode, &'static str), giving you control over the status code while still using the default text response.
This flexibility means you can choose the most convenient representation for each handler without writing boilerplate conversion code.
Everything works together:
When you run this example and visit /json in a browser, you'll see the JSON payload rendered. If you use a tool like curl, you'll also see the correct Content-Type header. This shows how the framework automatically handles both body and headers based on the return type.
Middleware - The Request/Response Pipeline
Middleware is code that runs around your handler. It can inspect or modify the request before it reaches the handler, and inspect or modify the response after the handler runs. Common uses include:
- Logging each request and its status code
- Authentication (checking if a user is logged in)
- Compression (gzip for large responses)
- Setting security headers
- Rate limiting
- Timeouts
In Axum, middleware is built on the Tower Service trait, which means you can use a huge ecosystem of ready-made middleware from tower-http. You can also write your own as a simple async function.
Here's a custom middleware that logs the method and path of every request, using Axum's middleware::from_fn:
use axum::{
extract::Request,
http::StatusCode,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
async fn logging_middleware(req: Request, next: Next) -> Result<Response, StatusCode> {
let method = req.method().clone();
let uri = req.uri().clone();
println!("Request: {} {}", method, uri);
let response = next.run(req).await;
println!("Response status: {}", response.status());
Ok(response)
}
async fn handler() -> &'static str {
"Hello from a logged request"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(middleware::from_fn(logging_middleware));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
When you run this server and send a request to /, you'll see two lines in your terminal: one before the handler runs and one after. The middleware has access to the request, can decide to short-circuit and return early (e.g., return 401 Unauthorized instead of calling next.run(req)), and can modify the response after the handler.
Middleware can be applied to the whole router (with .layer), to all routes registered so far but only when one of them matches (with .route_layer), or to a single route by calling .layer(...) on that route's method router. This gives you fine-grained control over which parts of your application get extra processing.
Middleware vs handlers:
A handler is the final destination for a request - it contains your specific business logic. Middleware is like a chain of assistants that process the request on the way in and the response on the way out. They don't replace handlers; they enhance them.
A Complete Tiny Example in Axum
Now let's put routing, extraction, response generation, and middleware together into one small but realistic web server. This server will:
- Have a
POST /usersroute that accepts a JSON body with a name and email. - Have a
GET /users/{id}route that returns a hardcoded user for any id. - Use a logging middleware to print each request.
Here is the full code:
use axum::{
extract::{Path, Json},
http::StatusCode,
middleware::{self, Next},
response::{IntoResponse, Response},
routing::{get, post},
Router,
};
use serde::{Deserialize, Serialize};
// Define the request and response data structures
#[derive(Deserialize)]
struct CreateUserRequest {
name: String,
email: String,
}
#[derive(Serialize)]
struct UserResponse {
id: u32,
name: String,
email: String,
}
// Handler for creating a user
async fn create_user(Json(payload): Json<CreateUserRequest>) -> impl IntoResponse {
// In a real app, you would save to a database.
// Here we just echo back with a fake ID.
let user = UserResponse {
id: 42,
name: payload.name,
email: payload.email,
};
(StatusCode::CREATED, Json(user))
}
// Handler for fetching a user by ID
async fn get_user(Path(id): Path<u32>) -> impl IntoResponse {
let user = UserResponse {
id,
name: "Alice".to_string(),
email: "alice@example.com".to_string(),
};
(StatusCode::OK, Json(user))
}
// Custom logging middleware
async fn log_requests(req: axum::extract::Request, next: Next) -> Result<Response, StatusCode> {
let method = req.method().clone();
let path = req.uri().path().to_string();
println!("Incoming: {} {}", method, path);
let response = next.run(req).await;
println!("Responded with: {}", response.status());
Ok(response)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", post(create_user))
.route("/users/{id}", get(get_user))
.layer(middleware::from_fn(log_requests));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Server running on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
Let's walk through what each part does:
- Data structures -
CreateUserRequestis the shape of the JSON body we expect from the client.#[derive(Deserialize)]tells theserdelibrary to automatically generate code that can parse JSON into this struct.UserResponsewith#[derive(Serialize)]does the reverse. create_userhandler - It takesJson<CreateUserRequest>as an argument. Axum reads the request body, parses the JSON, and if successful, calls the handler with the parsed data. The handler returns a tuple(StatusCode::CREATED, Json(user)), which becomes a201 Createdresponse with JSON body.get_userhandler - It takesPath<u32>, which extracts the{id}from the URL. It always returns a hardcoded user, but you can imagine a database lookup here.log_requestsmiddleware - It logs the method and path before calling the next step (the handler), then logs the response status after. It returnsOk(response)to signal success.mainfunction - Builds the router with the two routes, applies the middleware to all routes with.layer, binds a TCP listener on port 3000, and starts serving.
You can run this code with cargo run (assuming you've set up a Rust project with the required dependencies). Then use curl to test:
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name":"Bob","email":"bob@example.com"}'
Response:
{"id":42,"name":"Bob","email":"bob@example.com"}
And:
curl http://localhost:3000/users/7
Response:
{"id":7,"name":"Alice","email":"alice@example.com"}
In your terminal, you'll see the logging output for each request. This tiny example demonstrates all the major pieces a web framework provides, working together.
Serving and Graceful Shutdown
Starting the server is also the framework's job. axum::serve is intentionally simple: it accepts connections and runs your router until the process ends. It does not shut the server down gracefully on its own. Graceful shutdown is opt-in - you tell the server what to wait for, and it finishes the requests already in flight before it stops accepting new ones. The usual signal is Ctrl+C:
use axum::{routing::get, Router};
async fn handler() -> &'static str {
"Hello"
}
async fn shutdown_signal() {
tokio::signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(handler));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
}
With this in place, pressing Ctrl+C stops accepting new connections but lets handlers that are already running finish their work. Without it, the process exits immediately and any request in flight is cut off mid-response. The signal feature of Tokio must be enabled for tokio::signal::ctrl_c to exist - it is included when you enable Tokio's full feature.
Shutdown is a framework concern:
You could write shutdown handling yourself with raw sockets, but every server needs the same pattern: stop listening, drain in-flight work, then exit. Axum provides it as one method call because it is part of serving, not part of your application logic.
Common Misconceptions and Mistakes
As a beginner, you'll likely encounter a few confusing points. Here are the most important ones to avoid.
Not every error is a 500:
A common misunderstanding is that if something goes wrong in your handler, you must manually return a 500 Internal Server Error. Axum has a predictable error model: if your handler returns a Result and the error type implements IntoResponse, Axum will automatically convert errors into appropriate responses. For extractors, Axum already returns 400 Bad Request for malformed input. So don't wrap everything in unwrap() - let the framework handle errors gracefully.
Forgetting to enable Tokio features:
The examples above use #[tokio::main], which requires the macros and rt-multi-thread features of Tokio. If you see errors like cannot find attribute tokio::main``, add these features to your Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
Forgetting this is a frequent beginner stumbling block.
Start small and build up:
A great way to learn what a framework provides is to build the absolute smallest server that works, then add one feature at a time - a new route, an extractor, a middleware. Each addition teaches you one specific framework capability without overwhelming you. The examples on this page are intentionally minimal; build from there.
Frameworks are not magic:
Everything Axum does - routing, parsing, response conversion - happens in ordinary Rust code that you could write yourself. The value is that the framework has already written it, tested it, and made it composable. So when you see a "magical" extractor or response type, remember it's just a type implementing a trait. Understanding that removes the fear and helps you write your own extensions later.
Summary
A web framework like Axum exists to remove the repetitive, low-level details of HTTP handling so you can focus on your application's unique behavior. It provides routing, request parsing, response generation, and middleware as ready-to-use components, each backed by clear, type-safe Rust traits. Once you grasp these four pillars, you can start building real servers - and you'll spend your time on business logic instead of socket plumbing.
Before moving on, make sure the ideas on this page feel comfortable: try modifying the complete example, add a new route with a different extractor, or write your own tiny middleware. The more you experiment, the clearer the framework's role becomes.