axum routing get function

A beginner guide to using axum::routing::get to register handlers for HTTP GET requests in Axum applications

axum::routing::get is a function that connects a specific HTTP GET request to the Rust code that should handle it. It lives inside the routing module of the Axum crate, which is Axum's home for everything that maps incoming requests to the right piece of code. When a user opens your web application in a browser or sends a curl command with the GET method, this function is what eventually decides which handler gets to respond.

You will almost always use get together with Router::new() and the .route() method. The get function itself does not start a server or listen for traffic - it only builds a small piece of routing logic. In the simplest possible terms, get(handler) returns a description that says: "when a GET request arrives at the path I am attached to, run this handler." That description is then handed to the router.

Why get exists

HTTP is built around methods. A method is a word that tells the server what the client wants to do with a resource. GET is the most common method - it means "give me the data." When you type a URL into your browser's address bar, the browser sends a GET request. When you run curl http://localhost:3000, curl sends a GET request.

Axum needs a way to tell the router which method a handler should respond to. You could attach a handler that responds to every method, but that would be dangerous: an incoming POST request might accidentally trigger code that was only meant for reading data. So Axum splits route registration by method. get is the function for the GET method. There are companion functions like post, put, delete, and others, each named after the HTTP method it represents.

When you call get(handler), you are not yet routing anything. You are creating a MethodRouter - a small object that holds the handler and knows it should only be used for GET requests. Later, when you chain .route("/some/path", get(handler)), the router stores that MethodRouter under the given path. From then on, any GET request to that path is passed to your handler.

A first working example

Start from a fresh Axum project. If you have not created one yet, create a new binary crate, add axum and tokio with the full feature to Cargo.toml, and open src/main.rs. We will focus only on the get part, but the surrounding code is necessary for the server to run.

Here is a complete src/main.rs that answers every GET request to / with the text "Hello, World!":

// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    // Build the router with one GET route
    let app = Router::new().route("/", get(hello_world));
    // Bind a TCP listener to localhost port 3000
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    // Start serving requests
    axum::serve(listener, app).await.unwrap();
}
// The handler for GET /
async fn hello_world() -> &'static str {
    "Hello, World!"
}

When you run cargo run and open http://127.0.0.1:3000 in a browser or run curl http://127.0.0.1:3000, you see the exact text Hello, World!.

Look at the line that uses get:

.route("/", get(hello_world))

Here get takes one argument: the name of an async function. That function is called the handler. The router knows that hello_world should only be run when the request method is GET. If you try to access the same path with a POST request, Axum will reply with 405 Method Not Allowed because no POST handler exists.

Handlers must be async functions or closures

Axum handlers are ordinary Rust functions, but they must be declared with async. An async fn returns a future - a value that represents work that will finish later. Axum runs that future on an async runtime (Tokio) when a request arrives. This is why we put #[tokio::main] on the main function: it tells Tokio to take over and manage all async work.

The handler can be a named function, as in the example above, or a closure. A closure is a short anonymous function you write inline. Both work because Axum accepts anything that implements the Handler trait, and both named async functions and async closures implement it.

Here is the same route using an inline async closure:

// src/main.rs (excerpt)
let app = Router::new().route("/", get(|| async { "Hello from a closure!" }));

When you use a closure, you write || for the empty argument list, then async, then a block { ... } that returns the response. The closure itself does not need to be declared async; the async keyword goes inside the closure body to create an async block.

Both forms are equally valid. Named functions are easier to read and reuse. Closures are convenient for very short handlers that appear only once.

What can a handler return?

The handler after get must return something that implements the IntoResponse trait. That trait tells Axum how to turn the return value into an HTTP response with a status code, headers, and body.

Rust's standard string types already implement IntoResponse. For example:

  • &'static str - a string literal that lives for the entire program
  • String - a heap-allocated owned string
  • StatusCode - just an HTTP status code with no body
  • Tuples like (StatusCode, String) - a status code plus a body

A handler that returns &'static str produces a response with status 200 OK, the body set to that string, and a Content-Type header of text/plain; charset=utf-8. That is why the earlier example works so smoothly.

Here are three handlers returning different types, all valid with get:

// src/main.rs
use axum::{routing::get, Router, http::StatusCode};
async fn plain_text() -> &'static str {
    "plain text body"
}
async fn owned_string() -> String {
    format!("Current time: {:?}", std::time::SystemTime::now())
}
async fn only_status() -> StatusCode {
    StatusCode::NO_CONTENT
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/plain", get(plain_text))
        .route("/owned", get(owned_string))
        .route("/status", get(only_status));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Requesting /status returns an empty body with status 204 No Content. Requesting /owned returns a string built at request time. Notice that the handler can use local variables, call other functions, and do normal Rust work before returning the response - it is not limited to a single literal.

Registering a GET route step by step

The process of adding a GET route to an Axum application always follows the same order. If you are new to the framework, working through these steps one by one removes confusion.

1

Step 1: Import the get function and Router

At the top of src/main.rs, bring get and Router into scope:

use axum::{routing::get, Router};

Without this import, you would have to write axum::routing::get every time, which is noisy.

2

Step 2: Write the async handler function

Define a regular async function that returns something IntoResponse:

async fn hello() -> &'static str {
    "Hello"
}

The function name (hello) is what you will pass to get.

3

Step 3: Create a Router and chain route

Inside main, create a new Router and call .route() with the path and the get call:

let app = Router::new().route("/", get(hello));

The path / matches the root of your server. get(hello) produces the method-specific routing instruction.

4

Step 4: Bind a listener and serve

Bind a TCP listener, then hand it and the router to axum::serve:

let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();

After this, GET requests to http://127.0.0.1:3000/ are answered by hello.

This sequence is the same no matter how many routes you add. You repeat steps 2 and 3 for each new path and handler.

Combining get with other methods on the same path

A path can respond to more than one HTTP method. For example, a REST API often has GET /users to list users and POST /users to create a new one. Axum makes this possible by chaining method routers.

get(handler) returns a MethodRouter. That object has a .post(handler) method which returns another MethodRouter that now responds to both GET and POST. You can keep chaining methods as needed.

Here is an example with two handlers on the same /users path:

// src/main.rs
use axum::{routing::{get, post}, Router};
async fn list_users() -> &'static str {
    "List of users"
}
async fn create_user() -> &'static str {
    "User created"
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users", get(list_users).post(create_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now a GET request to /users returns List of users, and a POST request returns User created. A DELETE request to the same path would still get a 405 Method Not Allowed because no delete method was registered.

This chaining is part of the MethodRouter API, but get is what kicks it off. The important point is that get is not a one-time terminal operation; it returns an object you can extend with additional methods.

Common beginner mistakes

The most common mistakes with get involve the handler signature. Axum's compiler errors can be long, but they usually point back to one of these three issues.

Passing a non-async function

If you define a handler without the async keyword, the compiler will reject it when you pass it to get:

// This does NOT compile
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(not_async));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
fn not_async() -> &'static str {
    "I am not async"
}

The error will say something like the trait bound fn item ...: Handler<_, _> is not satisfied. That is Axum's way of saying "your function is not a valid handler." The fix is simple: add async before fn.

Non-async handler causes compile error:

A handler given to get must always be an async fn or an async closure. A regular synchronous function will never compile, no matter what it returns.

Returning something that does not implement IntoResponse

Even an async function can be rejected if its return type cannot be turned into an HTTP response. For example, a handler that returns u32 will not compile:

async fn number() -> u32 {
    42
}

Axum does not know how to convert a raw number into a response. The same is true for most custom structs unless you implement IntoResponse for them. For quick tests, return a String, &'static str, or StatusCode.

Forgetting the #[tokio::main] attribute

The main function must be async and annotated with #[tokio::main] to set up the Tokio runtime. Without it, you cannot use .await, and the server will not start. This is not specific to get, but it trips beginners who copy a get example and then wonder why nothing runs.

Missing tokio macros feature:

The #[tokio::main] macro requires the macros and rt-multi-thread features of Tokio. Using tokio with the full feature enables them automatically. If you add Tokio without features, the macro will not be available.

Variations of get with inline closures and named functions

You have already seen both a named function and an inline closure. Here is a side-by-side comparison of the two for the exact same route:

Named function:

// src/main.rs
use axum::{routing::get, Router};
async fn index() -> &'static str {
    "Home page"
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(index));
    // ...
}

Inline closure:

// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Home page" }));
    // ...
}

The behavior is identical. Choose the form that reads better in your codebase. Named handlers are the standard choice when the logic is more than one line or when you want to reuse the function in multiple places. Closures keep everything local and are great for tiny demos or one-off routes.

A practical example with multiple GET routes

Let's build a slightly larger router that uses get several times, each with a different handler and response type. This reinforces how get works in a real file and shows that you can mix return types freely.

// src/main.rs
use axum::{routing::get, Router, http::StatusCode};
async fn root() -> &'static str {
    "Welcome to the homepage"
}
async fn about() -> String {
    let app_name = "My Axum App";
    format!("About {app_name}")
}
async fn health() -> StatusCode {
    StatusCode::OK
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(root))
        .route("/about", get(about))
        .route("/health", get(health));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Here root returns a string literal, about returns an owned String, and health returns only a status code. When you request /health, Axum sends a 200 OK with an empty body. When you request /about, the response body changes based on the local variable app_name.

This example also shows that the order of .route() calls does not matter. Each path is independent.

How get works internally (mental model)

You do not need to understand the internals to use get, but a simple mental model helps you remember its role.

Think of get as a wrapper. It takes a handler function and wraps it into a MethodRouter object that carries two pieces of information: the handler itself and the HTTP method it should respond to. When you pass that MethodRouter to Router::route, the router stores it in a table keyed by the path.

When a request arrives, Axum compares the request's path and method against every entry in that table. If it finds a match, it calls the stored handler. If the path matches but the method does not, Axum knows to reply with 405 Method Not Allowed because the method routers for that path explicitly list which methods are allowed.

Without get, you would have to write custom code inside a single catch-all handler that manually checks req.method() == Method::GET and then runs the right logic. That is exactly what older low-level HTTP libraries required. get removes that boilerplate and makes the method restriction part of the router. A request that arrives with the wrong method is then answered at runtime with 405 Method Not Allowed, as you saw earlier - the method check happens when the request arrives, not at compile time.

A note on importing get

The official Axum examples often import get directly from axum::routing:

use axum::routing::get;

You can also import the whole routing module and then use routing::get:

use axum::routing;
let app = Router::new().route("/", routing::get(handler));

Or use a fully qualified path every time:

let app = Router::new().route("/", axum::routing::get(handler));

All three styles work. The direct import is the most common because it keeps the line short and matches the official documentation. Choose one style and stay consistent across your project.

Import grouping:

Many Rust developers group multiple Axum imports in one use statement: use axum::{routing::get, Router};. This is cleaner than writing separate use lines and is the style used throughout the official Axum docs.

What happens when you run the examples

After you add a get route and start the server, you can test it with curl. Open a second terminal while the server is running and type:

curl http://127.0.0.1:3000/

You should see the exact body returned by your handler. If you used the first example, the output is:

Hello, World!

You can also check the status code and headers with curl -i:

curl -i http://127.0.0.1:3000/

That shows something like:

HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 13
date: ...
Hello, World!

The content-type header is automatically set because Axum knows &'static str should be sent as plain text. Different return types set different headers. For example, returning Json sets application/json. For now, the plain text default is enough.

The relationship between get and Router::route

You might wonder why get is a function at all instead of just another argument to .route(). The reason is method composition. Router::route expects a MethodRouter, not a raw handler. get(handler) builds a MethodRouter for the GET method. If Axum allowed you to write .route("/", handler), it would have no idea which method the handler should answer to.

Because get returns a MethodRouter, you can also store it in a variable and attach it later. The variable needs a type annotation, because Rust cannot infer the router's state type from the get call alone:

use axum::{routing::{get, MethodRouter}, Router};
async fn handler() -> &'static str {
    "response"
}
#[tokio::main]
async fn main() {
    let get_method_router: MethodRouter = get(handler);
    let app = Router::new().route("/", get_method_router);
    // ...
}

This is rarely necessary but illustrates that get is independent of any particular path. A MethodRouter can be attached to more than one path if you clone it first - MethodRouter implements Clone - but you cannot move the same value into two .route() calls.

Summary

axum::routing::get is the entry point for handling HTTP GET requests in Axum. It takes an async function or async closure and returns a MethodRouter that you attach to a path via Router::route. The handler can return any type that implements IntoResponse - strings and status codes are the simplest, but the mechanism is extensible.

The key insight for a beginner is that routing in Axum is method-first: you always specify both a path and a method, and get is how you select the GET method. Once you understand that one function, the other method functions (post, put, delete) follow the exact same pattern. You are now ready to build a server that responds to browsers and curl commands for read-only endpoints.