API Versioning with Nest

Learn how to organize versioned API routes in Axum using the nest method and the /api/v1 path prefix pattern, including fallback behavior and multiple structuring approaches.

When an API grows, you eventually need to change its behavior without breaking existing clients. A mobile app released last year might still expect /users to return a list of names, while a new web frontend needs /users to return full profile objects. API versioning solves this by keeping old and new versions available at the same time, usually under different URL prefixes like /v1/users and /v2/users. In Axum, the nest method is the natural tool for grouping all routes of one API version under a common path prefix.

This page focuses on using nest to build versioned APIs with the /api/v1 style pattern. By the end, you will know how to structure multiple API versions cleanly, how fallbacks behave inside nested version routers, and which mistakes to avoid when first setting this up.

Why API Versioning Exists

Before writing any code, it helps to understand the real problem versioning solves. Imagine you run a public API. Many different applications call your endpoints. If you change the shape of a response or the meaning of a path parameter, those existing applications break. You could update every client at the same time as your server, but in practice that rarely works because you may not control all clients, or they update on different schedules.

Versioning gives you a way to introduce breaking changes safely. You keep the old version running unchanged, and you add a new version alongside it. Clients that are ready migrate to the new version on their own schedule. The old version can be removed later once you are confident nobody uses it anymore.

A common approach to versioning is to include the version number directly in the URL path. That is what we do with Axum by nesting routes under prefixes like /api/v1 and /api/v2. The nest method already handles prefix-based grouping, so we can reuse that pattern without any extra tooling.

Recap of the nest Method

The nest method attaches a router under a path prefix. It takes a path prefix and another Router. For example:

let app = Router::new()
    .nest("/users", users_router());

Here users_router() is a separate Router containing all routes that should live under /users. Any route defined inside that nested router gets the /users prefix automatically. A route defined as /profile inside the nested router becomes /users/profile from the outside.

That simple idea is exactly what we need for API versioning. We can build one router for version 1, another for version 2, and nest them under /api/v1 and /api/v2. The rest of this page shows how to do that in detail.

A Minimal Versioned API

Start with the smallest possible example. Suppose you have two endpoints: one that returns a simple greeting, and one that returns a user name. For version 1, the greeting is always "Hello". For version 2, the greeting takes a name query parameter and returns a personalized message. We want both versions available at the same time.

First, create the handlers. They are ordinary async functions that return impl IntoResponse.

use axum::{
    extract::Query,
    response::IntoResponse,
    routing::get,
    Router,
};
use std::collections::HashMap;
async fn v1_greeting() -> impl IntoResponse {
    "Hello from version 1"
}
async fn v2_greeting(Query(params): Query<HashMap<String, String>>) -> impl IntoResponse {
    let name = params.get("name").map(String::as_str).unwrap_or("world");
    format!("Hello, {}! This is version 2", name)
}
async fn v1_users() -> impl IntoResponse {
    // Imagine this returns a list of user names
    "v1 users: alice, bob"
}
async fn v2_users() -> impl IntoResponse {
    // Imagine this returns full user objects
    "v2 users: [{id: 1, name: 'alice'}, {id: 2, name: 'bob'}]"
}

Now build the version routers separately. Each version gets its own Router, and we define the routes inside that router using only the part of the path that comes after the version prefix.

fn v1_router() -> Router {
    Router::new()
        .route("/greeting", get(v1_greeting))
        .route("/users", get(v1_users))
}
fn v2_router() -> Router {
    Router::new()
        .route("/greeting", get(v2_greeting))
        .route("/users", get(v2_users))
}

Finally, in the main application builder, nest these version routers under their full prefixes.

#[tokio::main]
async fn main() {
    let app = Router::new()
        .nest("/api/v1", v1_router())
        .nest("/api/v2", v2_router());
    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 the server exposes four endpoints:

  • GET /api/v1/greeting
  • GET /api/v1/users
  • GET /api/v2/greeting?name=alice
  • GET /api/v2/users

Notice how clean the separation is. All version 1 logic lives in v1_router, all version 2 logic lives in v2_router, and the main Router only decides where they appear in the URL.

Everything Working:

If you run this code and send a request to /api/v1/greeting, you will see the exact string Hello from version 1. A request to /api/v2/greeting?name=alice returns Hello, alice! This is version 2. That different response under two different prefixes proves versioning is working.

Adding a Fallback Inside a Version Router

A fallback defined on a nested router only activates when no other route inside that nested router matches. It does not affect routes in other nested routers or in the outer router. You might wonder what happens when you add one inside a version router - the answer is that the fallback is scoped to that version alone.

Consider this extension of the previous example. Add a custom 404 fallback to the version 1 router:

async fn v1_not_found() -> impl IntoResponse {
    (axum::http::StatusCode::NOT_FOUND, "No such v1 endpoint")
}
fn v1_router() -> Router {
    Router::new()
        .route("/greeting", get(v1_greeting))
        .route("/users", get(v1_users))
        .fallback(v1_not_found)
}

Now a request to /api/v1/unknown returns No such v1 endpoint with status 404. But a request to /api/v2/unknown returns Axum's default 404 response, because the v2 router does not have its own fallback and the fallback from v1 does not apply outside that nested router.

If you want a consistent fallback across all versions, you can either add the same fallback to each version router, or define a fallback on the outer router that catches anything not matched by the nested routers.

Fallback Scope:

A fallback on a nested router is scoped to that nested router. It will not catch requests that miss the prefix entirely or that fall through in a sibling nested router. Keep this in mind when designing consistent error responses.

Nesting a Combined Version Router Under /api

The previous examples nest each version directly under a full path like /api/v1. That works perfectly and is easy to understand. However, as your API grows with many versions, you might want to group all version routers under a common /api prefix first. This gives you a single place to add middleware or fallbacks that apply to every version.

Instead of nesting v1_router and v2_router separately, create one combined router that itself nests each version under a short prefix.

fn api_router() -> Router {
    Router::new()
        .nest("/v1", v1_router())
        .nest("/v2", v2_router())
}
let app = Router::new()
    .nest("/api", api_router());

The resulting URLs are exactly the same as before: /api/v1/greeting, /api/v2/users, and so on. The difference is structural: now you have a dedicated api_router that contains everything API-related. You could add a fallback at this level to handle unknown API paths.

async fn api_not_found() -> impl IntoResponse {
    (axum::http::StatusCode::NOT_FOUND, "Unknown API endpoint")
}
fn api_router() -> Router {
    Router::new()
        .nest("/v1", v1_router())
        .nest("/v2", v2_router())
        .fallback(api_not_found)
}

Now any request under /api that does not match a known version and route gets Unknown API endpoint. This fallback does not affect routes outside /api. A request to /other still hits the outer router's default or custom fallback.

Both approaches are valid. The direct nesting style is simpler when you only have one or two versions. The combined router style becomes more valuable as the number of versions grows, because it keeps all API concerns in one place.

Working with Method Filters in Versioned Routes

You may have used method filters like get, post, or custom filters to control which HTTP methods a route accepts. Versioned routes can use these filters exactly the same way as any other route. The version prefix does not change how method filters work.

Suppose version 1 only allowed reading users with GET, but version 2 adds a POST endpoint to create a user. You would define those routes inside the respective version routers:

async fn v1_users() -> impl IntoResponse {
    "GET /users for v1"
}
async fn v2_get_users() -> impl IntoResponse {
    "GET /users for v2"
}
async fn v2_create_user() -> impl IntoResponse {
    "POST /users for v2"
}
fn v1_router() -> Router {
    Router::new()
        .route("/users", get(v1_users))
}
fn v2_router() -> Router {
    Router::new()
        .route("/users", get(v2_get_users).post(v2_create_user))
}

Now GET /api/v1/users works, but POST /api/v1/users returns 405 Method Not Allowed because only GET is allowed on that version's route. GET /api/v2/users and POST /api/v2/users both work because the v2 route registers both methods.

If you need a custom method filter inside a version router, combine standard methods with .or() and pass the result to routing::on, exactly as you would in a non-versioned router. For example, a route that accepts only GET and POST looks like this:

use axum::routing::{on, MethodFilter};
async fn v2_submit() -> impl IntoResponse {
    "v2 submit accepted"
}
fn v2_router() -> Router {
    Router::new()
        .route("/submit", on(MethodFilter::GET.or(MethodFilter::POST), v2_submit))
}

The version prefix changes nothing about how the filter works - the filter still applies to the route it is attached to, and only to that route.

Filters Are Per-Route:

Method filters do not leak between versions. Each route inside a nested router has its own filter configuration. Adding a POST endpoint to v2 does not add it to v1, and vice versa.

Step-by-Step Setup for a New Versioned API

If you are starting a new Axum project and want to set up API versioning from scratch, the following sequence shows a complete walkthrough. Each step builds on the previous one.

1

Step 1: Create the handler functions

Write one async function for each endpoint you need for version 1. These functions return impl IntoResponse. Keep them simple at first.

async fn v1_health() -> impl IntoResponse {
    "v1 healthy"
}
2

Step 2: Build the version 1 router

Create a function that returns a Router. Inside it, define routes for version 1 using only the path parts that come after /api/v1.

fn v1_router() -> Router {
    Router::new()
        .route("/health", get(v1_health))
}
3

Step 3: Add version 2 handlers and router

Create the handlers for version 2, which may differ from version 1. Then build a second router for version 2.

async fn v2_health() -> impl IntoResponse {
    "v2 healthy with more details"
}
fn v2_router() -> Router {
    Router::new()
        .route("/health", get(v2_health))
}
4

Step 4: Nest both version routers in the main app

In your main application builder, nest each version router under its full prefix.

let app = Router::new()
    .nest("/api/v1", v1_router())
    .nest("/api/v2", v2_router());

After completing these steps, your server responds at /api/v1/health and /api/v2/health, each with its own handler.

Common Mistakes and Misconceptions

Several mistakes trip up beginners when they first use nest for API versioning. The most important one is forgetting to define a route for the exact prefix path itself. The nest method matches any path that starts with the prefix, but it does not automatically create a route for an empty path under that prefix. For example, if you nest v1_router under /api/v1 and the inner router has no route for /, then a request to /api/v1 (without a trailing slash) will not match anything and will fall through to the outer fallback or default 404.

To handle the exact /api/v1 URL, add a route for / inside the version router:

fn v1_router() -> Router {
    Router::new()
        .route("/", get(v1_index))
        .route("/health", get(v1_health))
}

Now GET /api/v1 returns whatever v1_index provides. This is a subtle but real issue because many developers assume a nested router automatically handles the bare prefix.

Missing Root Route:

If you nest a router under /api/v1 and that inner router has no route for /, a request to exactly /api/v1 will not match any route in that inner router. It may fall through to another fallback or return a default 404, even though you might expect it to be part of version 1. Always define a root route if you want the prefix itself to respond.

Another common misconception is that a fallback on an inner router somehow overrides the outer router's fallback for paths outside the prefix. Fallbacks are scoped: a fallback inside v1_router only applies under /api/v1. It never affects /api/v2 or other top-level paths.

A third mistake is duplicating versioning logic by manually adding the prefix inside the handlers themselves. For example, trying to parse /api/v1 from the request path inside a handler is unnecessary and brittle. The whole point of nesting is that the prefix is handled once at the routing layer, and handlers stay clean.

Choosing Between Direct Nesting and a Combined API Router

At this point you have seen two ways to organize versioned routes: direct nesting of each version under its full prefix, and nesting a combined router under /api first. Which one should you use?

Use direct nesting when your application is small, or when the API versions are simple enough that you can see everything at a glance. It keeps the main router builder very explicit.

Use a combined API router when you anticipate many versions, when you want to apply common middleware or fallbacks to all API routes, or when you want to keep API-specific configuration in one module. The combined router also makes it easier to later move the entire API to a different prefix (for example, changing /api to /public-api) without touching the individual version routers.

Both approaches produce the same URLs and the same behavior. The choice is about long-term organization, not functionality.

Complete Example with Two Versions and a Fallback

To consolidate everything, here is a complete runnable example that includes two versions, different handlers, a fallback per version, and a root route for each version. This example can be placed in your main.rs for a typical Axum project.

use axum::{
    extract::Query,
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Router,
};
use std::collections::HashMap;
// --- Handlers for version 1 ---
async fn v1_index() -> impl IntoResponse {
    "Welcome to API v1"
}
async fn v1_greeting() -> impl IntoResponse {
    "Hello from v1"
}
async fn v1_users() -> impl IntoResponse {
    "v1 users: alice, bob"
}
async fn v1_not_found() -> impl IntoResponse {
    (StatusCode::NOT_FOUND, "v1 endpoint not found")
}
// --- Handlers for version 2 ---
async fn v2_index() -> impl IntoResponse {
    "Welcome to API v2 (improved)"
}
async fn v2_greeting(Query(params): Query<HashMap<String, String>>) -> impl IntoResponse {
    let name = params.get("name").map(String::as_str).unwrap_or("world");
    format!("Hello, {}! This is version 2", name)
}
async fn v2_users() -> impl IntoResponse {
    "v2 users: [{\"id\":1,\"name\":\"alice\"},{\"id\":2,\"name\":\"bob\"}]"
}
async fn v2_not_found() -> impl IntoResponse {
    (StatusCode::NOT_FOUND, "v2 endpoint not found")
}
// --- Version routers ---
fn v1_router() -> Router {
    Router::new()
        .route("/", get(v1_index))
        .route("/greeting", get(v1_greeting))
        .route("/users", get(v1_users))
        .fallback(v1_not_found)
}
fn v2_router() -> Router {
    Router::new()
        .route("/", get(v2_index))
        .route("/greeting", get(v2_greeting))
        .route("/users", get(v2_users))
        .fallback(v2_not_found)
}
// --- Main app ---
#[tokio::main]
async fn main() {
    let app = Router::new()
        .nest("/api/v1", v1_router())
        .nest("/api/v2", v2_router());
    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();
}

When you run this, you can test the following URLs:

  • http://127.0.0.1:3000/api/v1 returns Welcome to API v1 (note: the bare prefix, not /api/v1/ - the inner "/" route matches the prefix itself without a trailing slash)
  • http://127.0.0.1:3000/api/v1/greeting returns Hello from v1
  • http://127.0.0.1:3000/api/v2/greeting?name=alice returns Hello, alice! This is version 2
  • http://127.0.0.1:3000/api/v1/nonexistent returns v1 endpoint not found with status 404
  • http://127.0.0.1:3000/api/v2/nonexistent returns v2 endpoint not found with status 404

Each version has its own fallback, and both versions operate completely independently.

This Is the Goal:

If your output matches the descriptions above, you have successfully implemented API versioning with nest. The key takeaway is that each version lives in its own router, and nest connects it to a clean, predictable URL prefix.

Summary

API versioning with nest is a natural extension of Axum's routing model. By treating each API version as a separate Router and nesting it under a path prefix like /api/v1, you keep version-specific handlers, fallbacks, and method filters completely isolated. The main application router remains readable, and adding a new version becomes as simple as building another router and adding one more nest call.

The two structural choices - direct nesting per version versus a combined API router under /api - both produce the same URLs. Direct nesting is simpler for small projects; a combined router offers better organization and a single point for API-wide middleware or fallbacks as the API grows. Whichever style you pick, the core idea stays the same: use nest to give every API version its own clean URL space.