routing - post

Learn how to route HTTP POST requests in Axum using the post function, with practical examples, method matching, and common pitfalls.

When you build a web server, different HTTP methods serve different purposes. A GET request fetches data, a POST request usually creates new data or submits information. Axum gives you a dedicated function called post to tell the router: "when a POST request arrives at this path, run this handler." This page explains everything you need to know about routing::post from the ground up.

post works the same way as the other method-router functions: Router connects paths to handler functions, and post marks a handler as POST-only. That's the whole job of this one function - nothing more, nothing less. But there are important details about how it works under the hood, what handlers must return, and how to avoid common mistakes.

What routing::post Actually Does

post is a function that takes a handler function as its argument and returns a MethodRouter. That MethodRouter is the object you pass to Router::route. In simpler words: post(handler) produces a small router that only responds to POST requests. If a GET request arrives at the same path, Axum will not call this handler - it will look for a separate GET route or return 405 Method Not Allowed.

Here is the signature you will see in the official documentation:

pub fn post<H, T, S>(handler: H) -> MethodRouter<S, Infallible>
where
    H: Handler<T, S>,
    T: 'static,
    S: Clone + Send + Sync + 'static,

You do not need to memorize this. The key takeaway: post takes any valid handler and turns it into something that only matches the POST method. The S is the router's state type and Infallible is the error type - handlers cannot fail, so the error type is uninhabited. The T is the handler's extractor tuple; it is a parameter of the Handler trait, not of MethodRouter. For now, just treat post(handler) as "this handler responds to POST."

Why POST Needs Its Own Function

HTTP methods are part of the request line. When a browser or API client sends a request, it includes a method like GET, POST, PUT, or DELETE. A single URL can behave completely differently depending on the method. For example:

  • GET /users might return a list of users.
  • POST /users might create a new user.
  • PUT /users/5 might update user 5.
  • DELETE /users/5 might remove user 5.

Axum needs a way to distinguish these. That's why you have separate functions: get, post, put, patch, delete, and any. routing::post handles exactly the POST method. Without it, your server would not know what to do when someone submits a form or sends JSON data to create a resource.

A First Working Example

Let's start with the smallest possible POST route. This handler will accept a POST request and return a simple text response. We'll build the whole Axum application so you can run it and test with curl.

use axum::{
    routing::post,
    Router,
};
#[tokio::main]
async fn main() {
    // Build the application with one POST route
    let app = Router::new()
        .route("/submit", post(submit));
    // Start the server on localhost
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn submit() -> &'static str {
    "Form submitted successfully"
}

Run this with cargo run. Then open a second terminal and send a POST request:

curl -X POST http://127.0.0.1:3000/submit

You will see the response:

Form submitted successfully

This works because post(submit) registered the submit handler only for POST requests to /submit. If you try a GET request to the same path, Axum will respond with 405 Method Not Allowed because no GET handler exists.

You Have a Working POST Route:

If you see the text above, your route is correctly configured. Many beginners mistakenly think that defining a handler is enough - without post, the route would never match.

How post Fits Into Router::route

You have already seen Router::route used with get. The same method accepts post as its second argument. route expects a MethodRouter value, and post returns exactly that - MethodRouter is a struct, not a trait. You can call route multiple times on the same path with different method routers. Here is an example that supports both GET and POST on the same URL:

use axum::{
    routing::{get, post},
    Router,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users", get(show_users))
        .route("/users", post(create_user));
    // ... server setup omitted for brevity
}
async fn show_users() -> &'static str {
    "List of users"
}
async fn create_user() -> &'static str {
    "User created"
}

Because Axum allows multiple .route calls on the same path, you can attach different method handlers. The router will check the HTTP method and choose the right handler. This is the idiomatic way to handle both reading and writing on a single resource path.

Handler Requirements for POST

A handler used with post must meet the same requirements as any Axum handler: it must be an async function that returns a type implementing IntoResponse. In the examples above, &'static str implements IntoResponse, so it works. You can also return String, StatusCode, tuples, or custom response types.

What about function arguments? A handler can accept extractors - pieces of data parsed from the request. For POST requests, the most common extractors are Json and Form, which read the request body. We will show examples shortly. An extractor simply reads parts of the incoming request; the handler's parameters define what it expects, and post does not restrict which extractors your handler can use.

Example: Accepting JSON Data

A typical POST endpoint receives a JSON body. To keep this example focused on post, we'll use the Json extractor but not explain every detail of it. The important point is that the handler is passed to post and the router knows to call it only for POST requests.

The CreateUser struct below derives Deserialize from serde, so Cargo.toml needs serde with the derive feature:

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
use axum::{
    routing::post,
    Router,
    Json,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    username: String,
    email: String,
}
async fn create_user(
    Json(payload): Json<CreateUser>,
) -> String {
    format!(
        "Creating user {} with email {}",
        payload.username, payload.email
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test it with curl:

curl -X POST http://127.0.0.1:3000/users \
  -H "Content-Type: application/json" \
  -d '{"username":"alice","email":"alice@example.com"}'

The response will be:

Creating user alice with email alice@example.com

This example shows that post works perfectly with body-consuming extractors. If you sent the same request to a GET handler, the handler would run only if the route was registered with get; otherwise you'd get a 405.

Extractors Work With Any Method Router:

The post function does not care whether your handler uses Json, Form, Query, or any other extractor. The extractor just reads parts of the incoming request. The method router only guarantees that the handler is called when the HTTP method is POST.

Example: Handling Form Data

Another common use of POST is submitting HTML forms. Axum's Form extractor works similarly to Json but parses application/x-www-form-urlencoded data. Here is the same pattern using Form:

use axum::{
    routing::post,
    Router,
    Form,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct LoginForm {
    username: String,
    password: String,
}
async fn login(
    Form(form): Form<LoginForm>,
) -> String {
    format!("Logging in user {}", form.username)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/login", post(login));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test it:

curl -X POST http://127.0.0.1:3000/login \
  -d "username=bob&password=secret"

Response:

Logging in user bob

Notice that the handler signature changed only in the extractor type. The post(login) call is identical. This consistency is a big reason why Axum feels ergonomic: the method router does not dictate how you read the request body.

Multiple POST Routes on Different Paths

Real applications have many POST endpoints. You can register as many as you need by calling route multiple times on the same Router. Each call can use post with a different handler.

use axum::{
    routing::post,
    Router,
};
async fn create_article() -> &'static str {
    "Article created"
}
async fn create_comment() -> &'static str {
    "Comment created"
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/articles", post(create_article))
        .route("/comments", post(create_comment));
    // ... server startup
}

This is straightforward. You might wonder: can you combine these into a single route call? Not with post alone, because one call takes one method router. But a MethodRouter can chain multiple methods, for example get(show_users).post(create_user), which attaches two method handlers to the same path in one route call. For now, separate calls are clean and readable.

What Happens When a Wrong Method Hits a POST Route

When you register a route with post, Axum adds that route to its internal routing table with a method filter. If a request arrives with a different method (like GET, PUT, DELETE), Axum will look for another route at the same path that matches that method. If it finds none, it responds with 405 Method Not Allowed and includes an Allow header listing supported methods.

You can test this by sending a GET request to the /submit endpoint from the first example:

curl http://127.0.0.1:3000/submit

The response status will be 405 Method Not Allowed. The body is empty by default. The important thing is that your POST handler will not run for a GET request.

Method Mismatch Is Not a Handler Bug:

A common beginner mistake is to send a GET request to a POST route and think the handler has a bug because it never runs. The handler is working correctly; you just used the wrong HTTP method in your client.

Using post Inside Nested Routers

Sometimes you want to organize routes under a path prefix, like /api. Axum supports nesting routers with the nest method, which takes a path prefix and a second router whose routes are served under that prefix. When you nest a router that already has POST routes, those routes remain POST-only. Here is a quick illustration to show that post works inside nested routers just as well:

use axum::{
    routing::{get, post},
    Router,
};
async fn health_check() -> &'static str {
    "OK"
}
async fn create_item() -> &'static str {
    "Item created"
}
fn api_routes() -> Router {
    Router::new()
        .route("/health", get(health_check))
        .route("/items", post(create_item))
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .nest("/api", api_routes());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now POST /api/items will reach create_item, while GET /api/health will reach health_check. The method filter applied by post is preserved through nesting. You don't have to do anything special.

Using post with Closures

Handlers don't have to be named functions. You can pass closures directly to post. This is handy for tiny logic that doesn't deserve its own function. The closure must be async and return something that implements IntoResponse.

use axum::{
    routing::post,
    Router,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/ping", post(|| async { "Pong" }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This works because post accepts any type that implements the Handler trait, and async closures do. Just be careful with ownership and lifetimes - if your closure captures variables, you may need to use move.

Common Mistakes and How to Avoid Them

Forgetting to Import post

You must bring post into scope. The usual import is:

use axum::routing::post;

If you forget, the compiler will tell you that post is not found. This is easy to fix.

Mixing Up Handler Order in .route()

.route("/path", post(handler)) is correct. Some beginners reverse the order: .route(post(handler), "/path"). That won't compile because route expects a path string first, then a method router. Always path first, then post(...).

Expecting POST to Read Query Parameters Like GET

POST requests can include query parameters (?foo=bar) but typically carry data in the request body. If you need to read query parameters, use the Query extractor. But remember: post doesn't care where data comes from; it just matches the HTTP method. So you could use Query with a POST handler if the client sends query parameters. However, in practice, most POST handlers read the body.

Returning a Type That Doesn't Implement IntoResponse

Every handler must return a type that Axum knows how to convert into an HTTP response. &'static str, String, StatusCode, (StatusCode, String), and Json all implement IntoResponse. If you return something else, you'll get a compile error. Always check that your return type is valid.

Return Type Mismatch Causes Compile Errors:

If your handler returns, say, i32, the compiler will complain that i32 does not implement IntoResponse. You must return a valid response type. Common choices are String, Json<T>, or StatusCode. This is not specific to post - it applies to all handlers - but it trips up beginners often.

Testing POST Routes with Curl

You already saw basic curl commands. Here are a few more examples to help you verify your POST routes in different scenarios.

Test a route that returns plain text:

curl -X POST http://127.0.0.1:3000/endpoint

Test a route that expects JSON:

curl -X POST http://127.0.0.1:3000/users \
  -H "Content-Type: application/json" \
  -d '{"username":"alice","email":"alice@example.com"}'

Test a route that expects form data:

curl -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=bob&password=secret"

Check the response headers and status code:

curl -i -X POST http://127.0.0.1:3000/submit

The -i flag shows status line and headers, which is useful for debugging.

When Would You Use post Over Other Method Routers?

Use post when you want a handler to execute exclusively for POST requests. This is the standard way to create resources, submit forms, or perform actions that change server state. If you need a handler to respond to multiple methods, you can either call .route() multiple times with different method routers, or use a MethodRouter that chains methods - but that's a separate topic.

One nuance: POST is not idempotent. Sending the same POST request twice may create two resources. This is a property of HTTP, not Axum. Your handler logic must decide whether to enforce idempotency, but the routing layer simply matches the method.

How Axum Matches POST Requests Internally

When you call post(handler), Axum constructs a MethodRouter that contains your handler and a set of allowed methods (just POST). When a request arrives, the router first matches the path. Then it looks at the HTTP method. If the method is in the set of allowed methods for that path's MethodRouter, the handler runs. If not, the router continues searching for other routes. If none match, Axum returns 405 Method Not Allowed.

This process is efficient and happens before any handler body executes. That means if someone sends a GET to a POST route, your handler code never runs - Axum rejects it early.

Putting It All Together: A Small REST-like Example

Let's build a minimal API for a to-do list with just the POST parts to illustrate how post works in a realistic but still simple scenario. We'll have two POST endpoints: one to create a task, one to mark a task complete. We'll keep the handlers simple and avoid storing data - just return confirmation messages.

use axum::{
    routing::post,
    Router,
    Json,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct NewTask {
    title: String,
}
#[derive(Deserialize)]
struct CompleteTask {
    id: u32,
}
async fn create_task(
    Json(task): Json<NewTask>,
) -> String {
    format!("Task created with title: {}", task.title)
}
async fn complete_task(
    Json(task): Json<CompleteTask>,
) -> String {
    format!("Task {} marked complete", task.id)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/tasks", post(create_task))
        .route("/tasks/complete", post(complete_task));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test the first endpoint:

curl -X POST http://127.0.0.1:3000/tasks \
  -H "Content-Type: application/json" \
  -d '{"title":"Buy groceries"}'

Response:

Task created with title: Buy groceries

Test the second:

curl -X POST http://127.0.0.1:3000/tasks/complete \
  -H "Content-Type: application/json" \
  -d '{"id":42}'

Response:

Task 42 marked complete

This example shows two separate POST routes on different paths. Each uses its own handler and extractor. The post function keeps them method-specific, so a GET to /tasks will not trigger create_task.

Summary

routing::post is a small but essential piece of Axum routing. It takes a handler and wraps it with a method filter that only matches POST requests. You use it with Router::route to define what happens when a client sends a POST to a given path. Handlers can use any extractor, return any IntoResponse type, and can be named functions or closures. The main things to remember: import post, put the path before post(...) in .route(), and know that a wrong HTTP method results in 405 Method Not Allowed rather than calling your handler. With these basics, you can confidently build POST endpoints for forms, JSON APIs, and any other write operation your server needs.