update_user example signature
Learn how to write the handler signature for an update_user endpoint in Axum with correct extractor ordering, including multiple examples and common mistakes.
When you build a web API, updating a resource usually means two things: you need to know which resource to change, and you need the new data for that resource. In Axum, both pieces of information arrive through extractors, which are the arguments you put in a handler function. This page focuses on a concrete example: the update_user handler signature. We'll start from the simplest version and build it up, all while obeying one critical rule about the order of extractors.
If you have ever written a handler that takes a JSON body and a path parameter, you've already met this rule. But update_user makes it especially clear because it combines several extractor types, and getting the order wrong is a common beginner mistake. By the end of this page, you'll be able to write a correct update_user signature without hesitation and understand why it must look the way it does.
The Core Idea Behind update_user
An update_user handler is exactly what it sounds like: it receives a request asking to change an existing user's information. Typically, that request includes:
- A user ID to identify which user to modify. This usually comes from the URL path, like
/users/42. - The new data to apply, such as a new email address or name. This usually arrives in the request body, often as JSON.
To receive both, the handler function needs two extractors: a Path extractor for the ID and a Json extractor for the body. The signature must place them in the right order.
Let's look at the simplest possible update_user handler that does exactly that.
The Simplest update_user Signature
Start with a new Rust project and add the dependencies. In Cargo.toml:
[package]
name = "update-user-example"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Now, in src/main.rs, write the following complete program:
use axum::{
extract::{Path, Json},
routing::put,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct UpdateUser {
name: String,
email: String,
}
async fn update_user(
Path(user_id): Path<u32>,
Json(payload): Json<UpdateUser>,
) -> String {
format!("Updating user {} with name {} and email {}", user_id, payload.name, payload.email)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}", put(update_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Let's break down what's happening.
The update_user function has two parameters. The first is Path(user_id): Path<u32>, which extracts the {user_id} segment from the URL and tries to parse it as a u32. The second is Json(payload): Json<UpdateUser>, which reads the request body, expects it to be JSON, and deserializes it into the UpdateUser struct. Because UpdateUser derives Deserialize, Axum can convert the incoming JSON into that type automatically.
If you run this program and send a PUT request to /users/7 with a JSON body like {"name":"Alice","email":"alice@example.com"}, the handler returns the string Updating user 7 with name Alice and email alice@example.com. That confirms both extractors worked.
Everything Works:
If you see that output, the extractor order in this basic example is correct and your handler is functioning as intended.
But why must Path come before Json? Could we swap them? Let's answer that next.
Why the Order of Extractors Matters
Axum enforces a strict rule: a handler may have at most one extractor that consumes the request body, and that extractor must be the last argument. The Json extractor consumes the body. The Path extractor does not consume the body; it only reads from the URL, which is already available before the body is read. So Path goes first, Json goes last.
If you try to reverse the order, like this:
async fn update_user(
Json(payload): Json<UpdateUser>,
Path(user_id): Path<u32>,
) -> String {
// ...
}
You will get a compile error. The compiler reports that the Handler trait is not satisfied for the function, which is how Axum tells you the order is wrong. This is not a runtime issue; it is caught at compile time, which is one of Rust's strengths.
Compile Error If You Swap Them:
Placing a body-consuming extractor before a non-body extractor will cause a compilation failure: the compiler reports that the Handler trait is not satisfied for the function. Always keep body extractors like Json, Form, Bytes, or String as the final parameter.
The reason for this rule is that the request body is a stream that can only be read once. If you had two body extractors, you'd need to read the body twice, which is impossible without buffering the entire body. Axum avoids that by design.
Adding More Extractors to update_user
In a real application, you might also need other information from the request that does not come from the body. For example, you might need query parameters for pagination or headers for authentication. You can add as many non-body extractors as you like, as long as they appear before the single body extractor.
Consider an update_user that also accepts a Query parameter indicating which fields to update. Here's a more complete example.
First, define a struct for the query parameters:
use serde::Deserialize;
#[derive(Deserialize)]
struct UpdateOptions {
send_notification: Option<bool>,
}
Then modify the handler signature to include Query before Json:
use axum::extract::{Path, Query, Json};
async fn update_user(
Path(user_id): Path<u32>,
Query(options): Query<UpdateOptions>,
Json(payload): Json<UpdateUser>,
) -> String {
let notify = options.send_notification.unwrap_or(false);
if notify {
format!("Updating user {} and sending notification", user_id)
} else {
format!("Updating user {}", user_id)
}
}
Here, Query is another extractor that reads the URL query string and deserializes it into UpdateOptions. Because it does not consume the body, it can appear anywhere before Json. The order between Path and Query does not matter; you could swap them. But Json must remain last.
Let's see the complete main.rs for this version:
use axum::{
extract::{Path, Query, Json},
routing::put,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct UpdateUser {
name: String,
email: String,
}
#[derive(Deserialize)]
struct UpdateOptions {
send_notification: Option<bool>,
}
async fn update_user(
Path(user_id): Path<u32>,
Query(options): Query<UpdateOptions>,
Json(payload): Json<UpdateUser>,
) -> String {
let notify = options.send_notification.unwrap_or(false);
if notify {
format!("Updating user {} and sending notification", user_id)
} else {
format!("Updating user {}", user_id)
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}", put(update_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Test it with: curl -X PUT "http://127.0.0.1:3000/users/42?send_notification=true" -H "Content-Type: application/json" -d '{"name":"Bob","email":"bob@example.com"}'. The response will be Updating user 42 and sending notification.
Notice that send_notification is optional; if the query parameter is missing, the handler uses false as the default.
Why Query Goes Before Json:
Query reads from the URL, not the body. Since it doesn't consume the body, it can be placed anywhere before the body extractor. The only absolute rule is that the body extractor is last.
Common Pitfalls and How to Avoid Them
Even after understanding the rule, beginners often make a few predictable mistakes. Let's go through them one by one.
Mistake 1: Forgetting the Content-Type header
The Json extractor expects the request to include a Content-Type: application/json header. If you send a JSON body without that header, Axum will reject the request with a 415 Unsupported Media Type error and your handler will not run. This is not related to ordering, but it's a frequent source of confusion when testing with curl. Always include the header.
Missing Content-Type:
If you send a JSON payload without Content-Type: application/json, the Json extractor will reject the request before your handler runs. Use -H "Content-Type: application/json" in your curl command or set the header in your HTTP client.
Mistake 2: Using two body extractors
It might seem natural to accept both a JSON body and a raw string body in the same handler, perhaps for logging. But Axum forbids this because the body can only be consumed once. This is a compile-time error. If you need the raw body, consider using Bytes and then parsing it yourself, or use middleware.
// This will not compile
async fn update_user(
Json(payload): Json<UpdateUser>,
body: String, // second body extractor
) -> String {
// ...
}
Mistake 3: Putting a body extractor in the middle
Even if you only have one body extractor, putting it before a non-body extractor will fail. For instance:
// Fails because Json is not last
async fn update_user(
Json(payload): Json<UpdateUser>,
Path(user_id): Path<u32>,
) -> String {
// ...
}
The rule is not just "only one body extractor"; it's "body extractor must be the last argument". Always reorder so that all FromRequestParts extractors (like Path, Query, HeaderMap, State) come first, and the single FromRequest extractor (like Json, Form, String, Bytes) comes last.
Mistake 4: Assuming order among non-body extractors matters
It does not. You can place Query before Path or after; both are fine. The compiler does not care about the relative order of extractors that implement FromRequestParts. Only the body extractor's position is constrained.
Handling Rejection Gracefully with Result
By default, if an extractor fails (for example, the path parameter is not a valid u32, or the JSON body is malformed), Axum returns an error response and never calls your handler. But sometimes you want to handle that error inside the handler, perhaps to return a custom message. You can do this by wrapping the extractor in a Result.
For the update_user signature, you might want to catch cases where the Json deserialization fails. To do that, change the Json parameter to Result<Json<UpdateUser>, JsonRejection>:
use axum::{
extract::{Path, Json, rejection::JsonRejection},
http::StatusCode,
response::{IntoResponse, Response},
};
async fn update_user(
Path(user_id): Path<u32>,
payload: Result<Json<UpdateUser>, JsonRejection>,
) -> Response {
match payload {
Ok(Json(data)) => (
StatusCode::OK,
format!("Updated user {} with {}", user_id, data.email),
).into_response(),
Err(rejection) => {
let message = match rejection {
JsonRejection::MissingJsonContentType(_) => "Missing Content-Type header".to_string(),
JsonRejection::JsonDataError(_) => "Invalid JSON data".to_string(),
JsonRejection::JsonSyntaxError(_) => "Malformed JSON".to_string(),
_ => "Bad request".to_string(),
};
(StatusCode::BAD_REQUEST, message).into_response()
}
}
}
This version still keeps the body extractor last, but now the Result wraps it. The Path extractor remains first. Notice that the return type changed to Response because the handler now returns different status codes.
Why Wrap the Body Extractor in Result:
When you need custom error handling, wrapping the extractor in Result gives you access to the rejection reason. You can then choose what response to send. This is especially useful for JSON errors, where you may want to tell the client exactly what went wrong.
The full main.rs with this approach would look like:
use axum::{
extract::{Path, Json, rejection::JsonRejection},
http::StatusCode,
response::{IntoResponse, Response},
routing::put,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct UpdateUser {
name: String,
email: String,
}
async fn update_user(
Path(user_id): Path<u32>,
payload: Result<Json<UpdateUser>, JsonRejection>,
) -> Response {
match payload {
Ok(Json(data)) => (
StatusCode::OK,
format!("Updated user {} with {}", user_id, data.email),
).into_response(),
Err(rejection) => {
let message = match rejection {
JsonRejection::MissingJsonContentType(_) => "Missing Content-Type header".to_string(),
JsonRejection::JsonDataError(_) => "Invalid JSON data".to_string(),
JsonRejection::JsonSyntaxError(_) => "Malformed JSON".to_string(),
_ => "Bad request".to_string(),
};
(StatusCode::BAD_REQUEST, message).into_response()
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}", put(update_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Now, if you send a malformed JSON body, you'll get a 400 Bad Request with a message instead of Axum's default behavior.
A Complete update_user Route Example with All Extractors
Let's put everything together into a realistic update_user handler that uses several extractors: Path, Query, HeaderMap, and Json. This demonstrates that you can have many non-body extractors as long as the body extractor is last.
We'll include:
Path<u32>for the user ID.Query<UpdateOptions>for optional flags.HeaderMapto read a custom header likex-request-id.Json<UpdateUser>for the body.
Here's the full code:
use axum::{
extract::{Path, Query, Json},
http::{HeaderMap, StatusCode},
response::{IntoResponse, Response},
routing::put,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct UpdateUser {
name: String,
email: String,
}
#[derive(Deserialize)]
struct UpdateOptions {
send_notification: Option<bool>,
}
async fn update_user(
Path(user_id): Path<u32>,
Query(options): Query<UpdateOptions>,
headers: HeaderMap,
Json(payload): Json<UpdateUser>,
) -> Response {
let request_id = headers
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.unwrap_or("unknown");
let notify = options.send_notification.unwrap_or(false);
let message = format!(
"Request {}: updating user {} with email {} (notification: {})",
request_id,
user_id,
payload.email,
notify
);
(StatusCode::OK, message).into_response()
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}", put(update_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Notice the order: Path, Query, HeaderMap, then Json. All the non-body extractors come before Json. If you swapped HeaderMap and Json, it would fail.
HeaderMap Is Not a Body Extractor:
HeaderMap reads request headers, not the body, so it can be placed before Json. But it's still easy to accidentally place it after Json when you're adding extractors quickly. Always double-check that your body extractor is the final parameter.
When the Order Still Confuses You: A Deeper Look
If you've read everything so far and you're still wondering why Axum doesn't just allow any order and figure it out, the answer lies in how Rust's trait system works with extractors.
Axum distinguishes between two kinds of extractors:
FromRequestParts- extractors that only need the request's parts (method, URI, headers, extensions) and not the body. Examples:Path,Query,HeaderMap,Method,State.FromRequest- extractors that need access to the full request, including the body. Examples:Json,Form,String,Bytes,Requestitself.
A handler can have any number of FromRequestParts extractors, but only one FromRequest extractor. Axum's macro enforces this by requiring that the last parameter implement FromRequest. All earlier parameters must implement FromRequestParts. This is why the order is fixed by the type system: the compiler will reject a signature where a FromRequestParts extractor comes after a FromRequest one.
For a beginner, just remember this simple phrase: "Parts first, body last." Path, Query, HeaderMap, and State are all parts. Json, Form, String, and Bytes are body. Keep the body one at the end.
Summary
Writing an update_user handler in Axum comes down to one critical rule: the single body-consuming extractor must be the last argument. All other extractors can go before it in any order. This page walked through the simplest possible update_user signature, then added Query, HeaderMap, and error handling with Result, showing that the rule remains consistent.
The most important takeaway is not just to memorize the rule, but to understand why it exists: the request body can only be read once, and Axum's type system enforces that at compile time. Once you internalize that, you'll never struggle with extractor ordering again, not just for update_user but for any handler you write in Axum.