URLs, Paths, and Query Strings

Learn how URLs are structured, what path segments and query strings do, and how to read them from a browser or HTTP client.

A URL is the address you type into a browser to visit a website. When you request https://example.com/users/42?active=true, the web server receives more than just that address string. It receives a structured request where different parts of the URL carry different kinds of information.

This page explains two of those parts in detail: the path and the query string. Understanding how they work is essential before you build routes in Axum, because Axum reads both from every incoming request.

The parts of a URL

Before focusing on paths and query strings, it helps to see the full anatomy of a URL. Consider this complete example:

https://example.com:443/users/42?active=true&sort=name

A URL can be divided into several distinct pieces:

PartValue in the exampleWhat it identifies
SchemehttpsThe protocol used to transfer data
Hostexample.comWhich machine receives the request
Port443Which door on that machine to knock on
Path/users/42Which resource to retrieve or act on
Query string?active=true&sort=nameExtra parameters that modify the request

The scheme, host, and port answer the question "where do I send this request?" The path and query string answer "what exactly do I want once I get there?"

In Axum, the path and query string are the most important parts for routing and extracting data. The scheme, host, and port are already handled by the time your application code runs.

What a path is

The path is the portion of a URL that appears after the host and port, but before any ? character. In the URL https://example.com/users/42?active=true, the path is /users/42.

A path is a sequence of segments separated by forward slashes (/). The path /users/42 has two segments:

  • users
  • 42

Every path starts with a forward slash. The path / is called the root path. It has no segments at all - it is the empty path, the starting point of the hierarchy - not a segment of its own. When you visit the homepage of a website, the browser typically requests the root path.

Paths identify a specific resource or action on the server. In a well-designed HTTP API, the path tells you what kind of thing the request is about. The path /users might mean "the collection of all users," while /users/42 means "the single user whose identifier is 42."

Static and dynamic path segments

A path segment can be either static or dynamic.

A static segment is a literal word that never changes. In the path /users/42, the segment users is static. Every request for any user uses the same users segment.

A dynamic segment is a placeholder that varies from request to request. In /users/42, the segment 42 is dynamic. A different request might use /users/99 or /users/153.

The distinction matters because when you define routes in Axum, you write something like /users/{id}. The users part is literal text that must match exactly. The {id} part is a named placeholder that matches anything in that position and captures the value for later use.

Dynamic segments let a single route definition handle many different URLs. Without them, you would need to define a separate route for every possible user ID, which is obviously impossible when you don't know the IDs in advance.

Paths are hierarchical

A path resembles a file system structure. The forward slashes create a hierarchy where each segment narrows down the scope.

  • / is the root
  • /users is a collection of users
  • /users/42 is one specific user inside that collection
  • /users/42/orders is a collection of orders belonging to that user
  • /users/42/orders/7 is one specific order

This hierarchical nature is one reason paths feel intuitive to read. When you see a URL like /users/42/orders/7, you can guess what it refers to even without knowing the application's code.

Paths are not files:

Even though paths look like file system paths, they don't usually correspond to actual files on the server. In most web applications, the path is a logical identifier that the application code uses to decide what to do. The path /users/42 doesn't mean there is a file called 42 inside a folder called users on the disk.

What a query string is

The query string is the portion of a URL that comes after the ? character. In https://example.com/users?active=true&sort=name, the query string is active=true&sort=name.

A query string is a collection of key-value pairs separated by ampersands (&). Each pair uses an equals sign (=) to separate the key from the value.

The example above contains two pairs:

  • Key active, value true
  • Key sort, value name

Query strings are used to send optional parameters that modify how a resource is retrieved or processed. They don't usually identify the resource itself - the path does that. Instead, query strings provide filtering, sorting, pagination, search terms, and other modifiers.

Reading a query string as a beginner

When you see ?active=true&sort=name, reading it left to right reveals the structure:

  1. The ? marks the start of the query string.
  2. active=true is the first key-value pair.
  3. & separates this pair from the next one.
  4. sort=name is the second key-value pair.

Every & means "and here's another parameter." Every = means "this is the value for the key on the left."

Why the query string exists

The path works well for identifying a resource, but it doesn't handle optional parameters gracefully. Suppose you want to retrieve a list of users, but sometimes you want them filtered by status, sometimes sorted by name, and sometimes both.

You could try to put all of this in the path:

/users/active/sorted-by-name
/users/active/default-sort
/users/inactive/sorted-by-email

This quickly becomes unwieldy. The order of segments becomes significant, and you end up with many routes that all do almost the same thing. The query string solves this by providing a separate namespace for optional modifiers.

/users?status=active&sort=name
/users?status=active
/users?status=inactive&sort=email

The path remains clean and focused on the resource. The query string carries the variable parameters.

Query string keys and values are strings

When a browser sends a URL, every part of it is plain text. The value true in ?active=true is the string "true", not the boolean value true. The value 42 in ?limit=42 is the string "42", not the number 42.

This is a common source of confusion for beginners. When you read a query string in application code, you receive text and must convert it to the type you need. In Axum, extractors handle much of this conversion for you, but the underlying reality is always that query strings are made of text.

How paths and query strings work together

A path and a query string serve different roles in a request:

  • The path identifies which resource the request targets.
  • The query string modifies how that resource is retrieved or processed.

Consider an API endpoint that returns a list of products. The path /products identifies the product collection. A query string like ?category=books&max_price=30 narrows down which products to return.

The path answers "what am I looking at?" The query string answers "under what conditions?"

Where the question mark fits in

The ? character is the delimiter between the path and the query string. Everything before the ? is the path; everything after it (up to an optional # fragment, which we won't cover here) is the query string.

A URL can have a path but no query string:

https://example.com/users

A URL can also have a query string with no additional path segments:

https://example.com/search?q=rust

The query string is optional. The path is technically also optional in the sense that / is a valid path, but every HTTP request includes some path.

What happens when you submit a form

When you fill out an HTML form and click submit, the browser can send the form data as a query string if the form uses the GET method. For example, a search form on a website might send you to:

https://example.com/search?q=axum

The browser takes the input field named q, appends a ? to the target URL, and adds q=axum. If the form has multiple fields, the browser joins them with &.

This is why query strings often appear in your browser's address bar after submitting a search. The page doesn't load a different file - it loads the same /search path with a different query string.

A basic example with a simple server

To make these concepts concrete, here is a minimal Axum server that defines two routes: one for the root path and one for a /users path. The query string isn't processed yet - this example just shows how paths and query strings arrive as part of an HTTP request.

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(root))
        .route("/users", get(users));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn root() -> &'static str {
    "This is the root path"
}
async fn users() -> &'static str {
    "This is the /users path"
}

Run this server and open http://127.0.0.1:3000/ in a browser. You'll see the message "This is the root path." Now visit http://127.0.0.1:3000/users. You'll see "This is the /users path."

Now try http://127.0.0.1:3000/users?active=true. You'll see the same "This is the /users path" message. The query string didn't affect the route because the route only matches the path, not the query string.

This is an important detail: in Axum, routing decisions are based on the path alone. The query string is available for your handlers to read, but it doesn't determine which handler runs.

Extracting the path in Axum

When you define a route with a dynamic segment like /users/{id}, Axum captures the value in that segment and can pass it to your handler. The extractor for this is called Path.

Here is a complete example that reads a user ID from the path and returns it in the response:

use axum::{extract::Path, routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{id}", get(user_by_id));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn user_by_id(Path(id): Path<u32>) -> String {
    format!("You requested user {id}")
}

Open http://127.0.0.1:3000/users/42 and the response will be "You requested user 42." The dynamic segment {id} in the route definition matches the 42 in the URL, and the Path extractor captures that value as the Rust type u32.

The Path<u32> syntax tells Axum to take the captured string from the URL and convert it into a u32 integer. If the conversion succeeds, the handler runs. If it fails - for example, if you visit /users/hello - Axum returns an error response without ever calling the handler.

This conversion behavior is powerful because it means your handler receives a strongly typed value, not raw text. But it also means the dynamic segment must always be parseable as the declared type.

Path values are not validated by the route syntax:

Writing {id} in a route matches any text at that position. It doesn't restrict the segment to numbers, even if you declare Path<u32> in the handler. The type conversion happens after the route is matched. If you visit /users/hello, the route still matches, but Axum rejects the request with a 400 Bad Request because "hello" can't be parsed as a u32.

Capturing multiple path segments

A route can contain more than one dynamic segment:

use axum::{extract::Path, routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{user_id}/orders/{order_id}", get(order));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn order(Path((user_id, order_id)): Path<(u32, u32)>) -> String {
    format!("Order {order_id} for user {user_id}")
}

Here the route matches paths like /users/7/orders/19. The two dynamic segments are captured as a tuple (u32, u32), and the handler destructures them into the variables user_id and order_id.

When you visit http://127.0.0.1:3000/users/7/orders/19, the response is "Order 19 for user 7."

The order in the tuple matters. The first dynamic segment in the route becomes the first element of the tuple, and so on. This aligns with the left-to-right order of segments in the URL.

Extracting the path as a string

You don't always need to convert path segments to numbers. You can extract them as String when you need the raw text:

use axum::{extract::Path, routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/tags/{tag}", get(tag_info));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn tag_info(Path(tag): Path<String>) -> String {
    format!("Tag: {tag}")
}

Visit http://127.0.0.1:3000/tags/rust-web and the response is "Tag: rust-web." Because the extractor is Path<String>, Axum passes the segment through as text without any type conversion.

This is useful when path segments can contain arbitrary text, like slugs, usernames, or category names.

Extracting the query string in Axum

The query string is available to handlers through the Query extractor. The simplest form extracts all query parameters into a HashMap:

use axum::{extract::Query, routing::get, Router};
use std::collections::HashMap;
#[tokio::main]
async fn main() {
    let app = Router::new().route("/search", get(search));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn search(Query(params): Query<HashMap<String, String>>) -> String {
    let mut lines = Vec::new();
    for (key, value) in &params {
        lines.push(format!("{key} = {value}"));
    }
    lines.join("\n")
}

Open http://127.0.0.1:3000/search?q=axum&sort=newest and the response will list both key-value pairs:

q = axum
sort = newest

The Query extractor parses the query string and fills the HashMap with every key and its corresponding value as strings. The handler then iterates over the map and formats each pair.

HashMap order is not guaranteed:

A HashMap doesn't preserve the order of items. If you visit ?q=axum&sort=newest, the two pairs might appear in either order in the response. In practice, for two items the order may happen to match, but you should not rely on it. The key-value pairs in a URL do have an order, but the extractor stores them in a data structure that discards it.

Multiple values for the same key

A query string can legally repeat the same key. Consider ?tag=rust&tag=web. This says "the tag parameter is rust and also web." A HashMap<String, String> can't represent this because it only stores one value per key - if the key tag appears twice, the later value overwrites the earlier one.

Plain Axum Query cannot collect repeated keys into a Vec either: it is backed by serde_urlencoded, which does not support multi-value items, so a struct with a Vec<String> field will not gather every occurrence of the key. For repeated keys, use the Query extractor from axum-extra instead. It is backed by serde_html_form, which does support multi-value items and collects them into a Vec (or another sequential container) in order.

First, add axum-extra with the query feature:

[dependencies]
axum = "0.8"
axum-extra = { version = "0.12", features = ["query"] }

Then the same struct works as you would expect:

use axum::{routing::get, Router};
use axum_extra::extract::Query;
use serde::Deserialize;

#[derive(Deserialize)]
struct FilterParams {
    #[serde(default)]
    tag: Vec<String>,
    #[serde(default)]
    category: Vec<String>,
}

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

async fn filter(Query(params): Query<FilterParams>) -> String {
    format!(
        "tag = {}\ncategory = {}",
        params.tag.join(", "),
        params.category.join(", ")
    )
}

Visit http://127.0.0.1:3000/filter?tag=rust&tag=web&category=books. The response shows that both tag values are collected into a vector:

tag = rust, web
category = books

This pattern preserves every value for the named fields (tag, category) in order. The same split applies to form bodies: plain Axum Form uses serde_urlencoded, while axum-extra's Form (feature form) uses serde_html_form and collects repeated fields the same way.

Use the right Query for repeated keys:

If you import Query from axum and give a field a Vec<String> type, repeated keys will not be collected - that only works with axum_extra::extract::Query. Check your import when a multi-value parameter comes back with only one value (or a 400 Bad Request).

Extracting into a strongly typed struct

Working with a raw HashMap is flexible but forces your handler to do its own type conversions and error handling. A cleaner approach for structured query strings is to extract directly into a Rust struct using serde:

use axum::{extract::Query, routing::get, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct SearchParams {
    q: String,
    limit: u32,
    active: Option<bool>,
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/search", get(search));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn search(Query(params): Query<SearchParams>) -> String {
    match params.active {
        Some(true) => format!("Searching '{}' with limit {} (active only)", params.q, params.limit),
        Some(false) => format!("Searching '{}' with limit {} (inactive only)", params.q, params.limit),
        None => format!("Searching '{}' with limit {}", params.q, params.limit),
    }
}

This handler expects a query string like ?q=axum&limit=20&active=true. The SearchParams struct declares three fields:

  • q is a required string
  • limit is a required u32 integer
  • active is an optional boolean

The Option<bool> type for active means the query string can omit this key entirely. If ?active= is absent, params.active will be None, and the handler falls through to the final None branch.

When you visit http://127.0.0.1:3000/search?q=axum&limit=20&active=true, the response is:

Searching 'axum' with limit 20 (active only)

If you visit http://127.0.0.1:3000/search?q=axum&limit=20 without the active key, the response is:

Searching 'axum' with limit 20

This struct-based approach moves the responsibility for parsing and validating the query string from your handler body into the extractor layer. The handler receives a fully populated struct with the correct Rust types.

Missing required query keys cause an error:

The q and limit fields are not Option types, so the query string must include them. If you visit /search?q=axum without a limit, Axum rejects the request with a 400 Bad Request because the extractor can't construct a SearchParams. The same happens if limit can't be parsed as a u32, for example ?q=axum&limit=twenty. Always check which fields are optional and which are required when you design your struct.

Query values are always strings on the wire

Even when you use a strongly typed struct, the actual data in the URL is text. The query string ?limit=20 contains the characters 2 and 0, not a binary integer. The Query extractor uses serde to parse that text into a u32 before your handler runs.

This conversion can fail, and when it does, the request is rejected before reaching your handler. The error handling is centralized, which means you don't write if checks for every field in every handler.

Decoding special characters in URLs

URLs can't contain every character directly. Spaces, accented letters, punctuation like & or ?, and non-ASCII text must be percent-encoded before being placed in a URL.

Percent encoding replaces a character with a % followed by two hexadecimal digits that represent the character's byte value. A space becomes %20. An ampersand in a value becomes %26. The string hello world in a query value becomes hello%20world.

This matters because the Query extractor automatically decodes percent-encoded text before passing it to your handler. If you send ?q=hello%20world, the handler receives "hello world".

Here is an example that returns a query parameter verbatim so you can observe the decoding:

use axum::{extract::Query, routing::get, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct MessageParams {
    message: String,
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/echo", get(echo));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn echo(Query(params): Query<MessageParams>) -> String {
    params.message
}

Visit http://127.0.0.1:3000/echo?message=hello%20world. The response body will be:

hello world

The browser displays %20 in the address bar, but the server receives the decoded space. If you typed a literal space in the URL, the browser would encode it as %20 before sending the request, so the same result occurs.

The ampersand problem in query values

The ampersand is the separator between key-value pairs. If a value needs to contain a literal ampersand, it must be percent-encoded as %26.

Consider a query string where the search term is rust & axum:

?q=rust%20%26%20axum

If you wrote ?q=rust & axum without encoding, the parser would see three parts:

  • q=rust (with a trailing space)
  • An empty segment before axum
  • axum treated as a key with no value

The %26 tells the parser "this ampersand is part of the value, not a separator."

The same principle applies to = inside values, which must be encoded as %3D, and ? inside values, which must be encoded as %3F if you want it treated as data rather than a delimiter.

If you ever need the path segment exactly as it arrived over the wire, still percent-encoded, Axum has a RawPathParams extractor for that. Most handlers never need it - Path gives you the decoded value, which is what you usually want.

Fragments never reach the server, and trailing slashes matter

Two small URL details catch beginners out, so they belong here rather than as surprises later.

A URL can end with a fragment, the part after a #, like the #pricing in https://example.com/docs#pricing. The fragment is for the browser only: it tells the browser which part of the page to scroll to. The browser strips the fragment before sending the request, so the server never sees it. Axum cannot read a fragment because it never arrives. Anything the server needs to know must travel in the path, the query string, a header, or the body - never in the fragment.

A trailing slash changes the path. In Axum, /users and /users/ are two different paths. A route registered as /users matches a request for /users but not for /users/, and a route registered as /users/ matches only the version with the slash. If a client gets a 404 Not Found for a path that looks right, check the trailing slash first - it is one of the most common causes of a route that "should" match but does not.

Don't build query strings by hand:

When you need to construct a URL with dynamic values in application code, don't manually concatenate strings with & and =. Use a URL encoding utility or the query serialization that your HTTP client provides. Forgetting to encode a value breaks the URL structure and produces subtle bugs that are hard to trace.

How browsers handle paths and query strings

When you type http://127.0.0.1:3000/users/42?active=true into a browser's address bar, the browser parses the URL, establishes a connection to 127.0.0.1 on port 3000, and sends an HTTP request that includes the path and query string as separate components.

The browser displays the full URL including the query string. If the URL contains percent-encoded characters, the browser typically shows the encoded form in the address bar.

When you follow a link on a web page, the link's href attribute can include both a path and a query string. The browser sends the query string along with the path when the link is clicked.

The query string is visible to the user

Any data sent via a query string is visible in the browser's address bar, appears in browser history, and can be bookmarked. This is by design. Query strings are intended for non-sensitive, optional parameters.

Sensitive information like passwords, authentication tokens, or personal identifiers should not be sent via query strings. They should be sent in request bodies or headers instead. Query strings are also typically logged by servers, proxies, and analytics tools.

The path is also visible

Paths are equally visible. The path /users/42 reveals that there is a user with identifier 42. Whether that matters depends on the application. Some applications use random opaque identifiers in paths precisely because they don't reveal useful information about the underlying database.

Common mistakes and misunderstandings

Newcomers to HTTP APIs often conflate paths and query strings or misuse one in place of the other. Here are the most frequent problems.

Using a query string to identify a resource

A request like GET /users?id=42 uses a query string to identify which user to fetch. This is not wrong from a technical perspective - the server can absolutely read id=42 from the query string and respond with that user.

However, the path /users/42 is more conventional for identifying a single resource. Using the path for identity makes the URL structure clearer and allows routing logic to handle the resource directly. Many HTTP clients and caching layers also treat paths as more significant than query strings when forming cache keys.

There are exceptions. Search endpoints use query strings because the query parameters describe a search rather than identify a specific resource: /search?q=axum.

Overloading the path with too many optional parameters

Suppose you want to filter a product list by category, price range, availability, and sort order. Putting all of these in the path produces something like:

/products/books/under-30/in-stock/sorted-by-price

This route requires a fixed order for the segments, makes it impossible to omit a filter (what if you don't care about category?), and is difficult to extend. A query string handles this naturally:

/products?category=books&max_price=30&in_stock=true&sort=price

Each parameter is optional in a query string. The path stays short and stable.

Forgetting that query keys are case-sensitive

The query string ?Active=true and ?active=true are different. Keys are case-sensitive, so a struct with a field named active won't match a query key Active unless you explicitly configure serde to accept different names.

This applies to paths too. The path /Users and /users are distinct routes.

Assuming query string order matters

The order of query string pairs typically doesn't affect how a well-built API interprets them. The query strings ?a=1&b=2 and ?b=2&a=1 are semantically equivalent. If your handler uses a HashMap, the order is irrelevant. If you use a struct with serde, the field order is defined by the struct, not the URL.

There are rare cases where order matters, such as when the same key appears multiple times and you want to preserve the sequence of values. But for distinct keys, order is not semantically meaningful.

Confusing the ? with the start of the value

The ? character appears exactly once in a URL to mark the start of the query string. Everything after it is query string data. If a query value itself needs to contain a literal ?, that character must be percent-encoded.

A URL can only have one query string. The path cannot contain a ? because the ? terminates the path.

Missing the slash between path segments

In a route like /users/{id}, the slash between users and {id} is part of the route. If you write /users{id}, the route matches paths like /users42 - a completely different structure.

Slash placement matters. /users/42 has two segments; /users42 has one segment.

Watching requests arrive in real time

One of the best ways to build intuition about paths and query strings is to observe them in actual HTTP requests. You don't need special tools for this. A browser's developer console (usually opened with F12) has a Network tab that shows every request your browser sends, including the full URL.

When you visit http://127.0.0.1:3000/users/42?active=true, the Network tab shows a request entry with the full URL. Clicking on that entry reveals the request line, which contains the method, path, and query string exactly as the server sees them.

Command-line tools like curl also show this clearly. Running:

curl http://127.0.0.1:3000/users/42?active=true

sends a GET request for the path /users/42 with the query string active=true. The output is whatever your handler returns.

If you want to see the raw HTTP request line, add the -v flag:

curl -v http://127.0.0.1:3000/users/42?active=true

The verbose output includes a line like:

GET /users/42?active=true HTTP/1.1

This line is what the server actually receives. The method, path, and query string are all present in a single line of text, but the HTTP protocol defines how to split them into separate pieces.

How Axum separates the path and query string

When an HTTP request arrives at an Axum application, the underlying HTTP engine parses the request line into its components: method, path, and query string.

Axum's router uses only the path component for matching routes. It looks at the path, finds the route definition whose pattern matches, and invokes the corresponding handler.

The query string is not used for route matching, but it is stored in the request and can be extracted by the handler using the Query extractor.

This separation means you can define two different routes that share the same path but differ in query string, and Axum will treat them as the same route. The handler must then inspect the query string to differentiate between the two cases if needed.

What the handler sees

From the handler's perspective, the path and query string arrive through different extractors. The Path extractor pulls values from dynamic path segments. The Query extractor pulls values from the query string.

A single handler can use both:

use axum::{extract::{Path, Query}, routing::get, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct PageParams {
    page: Option<u32>,
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{id}", get(user_details));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn user_details(Path(id): Path<u32>, Query(params): Query<PageParams>) -> String {
    match params.page {
        Some(page) => format!("User {id}, page {page}"),
        None => format!("User {id}, no page specified"),
    }
}

Visit http://127.0.0.1:3000/users/7?page=3. The Path extractor captures 7 from the path, and the Query extractor captures page=3 from the query string. The response is:

User 7, page 3

Visit http://127.0.0.1:3000/users/7 without a query string. The page field is None, and the response is:

User 7, no page specified

The handler receives both pieces of information cleanly separated and already converted to the appropriate Rust types.

This combination is the core pattern:

Combining Path for identity and Query for modifiers is one of the most common patterns in Axum applications. When you see a handler that takes both Path<...> and Query<...>, you know the route identifies a specific resource and the query string configures how to handle it. This pattern appears again and again in real Axum codebases.

Summary

The path and query string are two sides of the same coin. The path is a hierarchical sequence of segments that identifies a resource. The query string is a flat collection of key-value pairs that modifies how that resource is processed.

Axum routes requests based on the path alone. Dynamic segments like {id} capture variable parts of the path and pass them to handlers via the Path extractor. The query string is available through the Query extractor, which can deliver the data as a HashMap or as a strongly typed struct via serde.

The conceptual split is simple: if the information identifies what you're talking about, it belongs in the path. If it qualifies how you want to retrieve or process it, it belongs in the query string. Once you internalize that split, both reading other people's APIs and designing your own become significantly easier.