Enabling the Query Feature Flag in Axum
Learn what Cargo feature flags do, how the query feature controls Axum's Query extractor, and how to configure it correctly in your project.
Rust's package manager, Cargo, lets crate authors split their code into optional pieces called feature flags. When you add Axum to your project, not every built-in extractor is compiled into your application by default. Some are gated behind named switches that you turn on in your Cargo.toml file. The Query extractor is one such piece, and this page explains exactly how to make it available and what happens when you get the configuration wrong.
The Query extractor reads URL query parameters like ?page=2&per_page=50 and turns them into a typed Rust value. It works out of the box because the default Axum configuration turns on the query feature automatically. This page pulls back the curtain on that default, shows you how to take explicit control of it, and prepares you for projects that disable default features entirely.
What a Cargo Feature Flag Actually Is
A feature flag is a named switch inside a Rust crate's Cargo.toml metadata that conditionally includes or excludes parts of the crate's source code. When you write a dependency declaration, you can list which features you want:
[dependencies]
axum = { version = "0.8", features = ["query"] }
The features list tells Cargo to pass a specific compilation marker to the Axum source code. Axum's internal code looks at that marker and decides whether to compile the Query extractor module or skip it entirely.
This matters for three practical reasons. First, it keeps the compiled binary smaller - if you never use WebSockets, Axum does not need to include all the WebSocket machinery in your final executable. Second, it reduces compile time because the Rust compiler never processes the unused code paths. Third, it keeps the crate maintainable - the Axum team can develop many capabilities in parallel without forcing every user to accept every dependency.
For an absolute beginner, the mental model is simple: feature flags are like checkboxes on a configuration form. The crate ships with every checkbox fully assembled, but only the checked boxes get packed into your final program.
The query Feature in Axum
Axum defines a feature named query that gates the axum::extract::Query extractor. When that feature is enabled, the Query type exists and works exactly as described in the extractor pages. When it is disabled, the type simply does not exist at compile time, and any handler that tries to use it will fail with a "cannot find type" compiler error.
The feature name in Cargo.toml is written as a plain string: "query". The Rust import path is written with uppercase Query: use axum::extract::Query;. These are two different spellings for two different purposes, and confusing them is a common beginner stumble.
Feature names are lowercase:
Cargo feature names in Cargo.toml are always written in lowercase - "query", "json", "form", "ws". The Rust type you import is Query with a capital Q. The feature name and the type name are related but not interchangeable.
How Axum Defaults Save You Configuration Work
Axum ships with a set of default features. These are features that are automatically enabled when you write the simplest possible dependency declaration:
[dependencies]
axum = "0.8"
In Axum 0.8, the default feature set includes query, along with json, form, tokio, http1, tracing, and several other commonly used capabilities. This is why the Query extractor works without any special setup: the default configuration already includes it.
The trade-off is that default features are opinionated. If you are building an embedded system with tight binary size constraints, or a high-security service that wants to minimize its attack surface, you might not want every default feature compiled in. Axum gives you a way to opt out, and once you do, you must opt back into each feature you actually need.
Explicitly Enabling the query Feature
Even when default features already include query, writing the dependency declaration explicitly is a good habit. It documents your intent and protects you if Axum ever changes its default feature set in a future version.
Here is the explicit form:
[dependencies]
axum = { version = "0.8", features = ["query"] }
This is not a replacement for default features - it adds the query feature on top of the default set. If Axum 0.9 ever removed query from the defaults, this declaration would continue to work because you are stating the requirement directly.
You can combine multiple explicit features in the same list:
[dependencies]
axum = { version = "0.8", features = ["query", "json", "form"] }
Each entry in the list is a separate feature that gets added to whatever the defaults already provide.
Working Without Default Features
The more advanced scenario is disabling all default features and building your feature set from scratch. This is done with the default-features = false key:
[dependencies]
axum = { version = "0.8", default-features = false, features = ["query", "tokio", "http1"] }
This tells Cargo to enable nothing automatically. Only the features you explicitly list - query, tokio, and http1 in this case - plus any that those features themselves depend on, will be compiled.
The tokio and http1 features deserve attention here. Axum is built on the Tokio async runtime, and axum::serve needs both of them: tokio for the runtime and http1 for HTTP/1.1 support (the alternative is http2). Without both, the serve function does not exist at all, and the compiler reports cannot find function 'serve' in crate 'axum'. That error looks strange the first time you see it, because your code never mentions a feature flag, but it means exactly one thing: the serving machinery was not compiled in.
Missing tokio or http1 when default features are off:
If you write default-features = false without "tokio" and "http1", your project will fail to compile with cannot find function 'serve' in crate 'axum'. Both are needed for axum::serve: tokio provides the async runtime and http1 provides HTTP/1.1 support. Always include both when you disable defaults and serve over HTTP/1.1.
A Complete Minimal Project with Explicit Feature Configuration
Here is an entire working project that uses the query feature explicitly. Create a new Cargo project and fill in the files as shown.
Cargo.toml:
[package]
name = "query-flag-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", features = ["query", "tokio"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
src/main.rs:
use axum::{
extract::Query,
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
per_page: Option<u32>,
}
async fn list_items(
Query(pagination): Query<Pagination>,
) -> String {
let page = pagination.page.unwrap_or(1);
let per_page = pagination.per_page.unwrap_or(20);
format!("Showing page {page} with {per_page} items")
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/items", get(list_items));
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();
}
This is the same handler structure you would write with default features - the only difference is the explicit features = ["query", "tokio"] declaration in Cargo.toml. When you run cargo run and visit http://127.0.0.1:3000/items?page=3&per_page=15, the server responds with Showing page 3 with 15 items. The explicit configuration changes nothing about runtime behavior; it only changes what the compiler includes in the build.
Verifying your feature configuration works:
If the server compiles and responds correctly with query parameters, your query feature is enabled and the Query extractor is functioning. The explicit features list in Cargo.toml is the source of truth for what got included.
What Happens When query Is Missing
The most instructive scenario is the failure case. Take the same project as above but remove query from the features list:
[dependencies]
axum = { version = "0.8", features = ["tokio"] }
Now run cargo build. The compiler processes src/main.rs and reaches the line use axum::extract::Query;. It searches the compiled Axum crate for a module named extract and inside that for a type named Query. Because the query feature was not enabled, that type was never compiled into Axum. The compiler reports an error resembling:
error[E0433]: failed to resolve: could not find `Query` in `extract`
--> src/main.rs:2:14
|
2 | extract::Query,
| ^^^^^ could not find `Query` in `extract`
This is a compile-time failure, not a runtime failure. The error appears before your server ever starts. That is the benefit of feature flags - they fail loudly and immediately at build time rather than silently misbehaving when requests arrive.
Import path failures are the first clue:
If you see "could not find Query in extract" or a similar unresolved import error, check Cargo.toml before changing your code. In almost every case, the type is missing because its feature flag is not enabled, not because you wrote the wrong import path.
A Server with Query Disabled but Other Features Working
To prove that the rest of Axum still functions without query, here is a project that disables default features, enables tokio, http1, and the json feature, and deliberately leaves out query:
Cargo.toml:
[package]
name = "no-query-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", default-features = false, features = ["tokio", "http1", "json"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
src/main.rs:
use axum::{
extract::Json,
routing::post,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateItem {
name: String,
quantity: u32,
}
async fn create_item(
Json(payload): Json<CreateItem>,
) -> String {
format!(
"Created {} ({} units)",
payload.name, payload.quantity
)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/items", post(create_item));
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();
}
This server accepts POST requests with JSON bodies and responds with a confirmation string. It compiles and runs because json is explicitly enabled. If you tried to add a handler parameter of type Query<Pagination>, the compiler would reject it because the query feature was never activated. Each extractor's feature flag is independent - enabling one has no effect on another.
The practical lesson is that default-features = false gives you fine-grained control, but you must account for every extractor your handlers actually use. Forgetting one produces an import error that is easy to fix once you know what the error means.
Combining Query with Other Features Without Defaults
Here is a complete configuration that disables defaults, enables query and json together, plus the tokio and http1 features that serving needs, and demonstrates both extractors working side by side:
Cargo.toml:
[package]
name = "query-json-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", default-features = false, features = ["tokio", "http1", "query", "json"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
src/main.rs:
use axum::{
extract::{Json, Query},
routing::{get, post},
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
per_page: Option<u32>,
}
#[derive(Deserialize)]
struct CreateItem {
name: String,
quantity: u32,
}
async fn list_items(
Query(pagination): Query<Pagination>,
) -> String {
let page = pagination.page.unwrap_or(1);
let per_page = pagination.per_page.unwrap_or(20);
format!("Listing page {page}, {per_page} items")
}
async fn create_item(
Json(payload): Json<CreateItem>,
) -> String {
format!("Created {} ({} units)", payload.name, payload.quantity)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/items", get(list_items).post(create_item));
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();
}
Run the server and exercise both endpoints. A GET request to /items?page=4&per_page=10 returns Listing page 4, 10 items. A POST request to /items with body {"name": "Notebook", "quantity": 7} and header Content-Type: application/json returns Created Notebook (7 units).
This example demonstrates two features working together under a minimal configuration. The features list is explicit and complete - nothing is implicit, nothing is accidental. If you remove "query" from that list, the GET handler breaks at compile time. If you remove "json", the POST handler breaks. Each feature you list is a contract between your code and the crate.
Checking What Features an Axum Project Has
When you inherit a project or add Axum to an existing codebase, you may not know which features are currently enabled. The fastest way to check is with Cargo's built-in tree command:
cargo tree -e features -p axum
This prints a tree showing the Axum dependency and every feature that is currently active. The output includes lines like axum feature "query" when the feature is enabled. If you do not see that line, the Query extractor is not available in this project.
Another useful command:
cargo tree -e features
This shows feature status for every dependency, not just Axum. It can be noisy in a large project, but it is the definitive source of truth for what your build actually includes.
Cargo tree is your debugging friend:
When you encounter a "could not find type" error and your Cargo.toml looks correct, run cargo tree -e features -p axum to confirm what actually got compiled. Dependency resolution can be affected by other crates, and the tree command reveals the final resolved state.
How Other Extractors Compare in Their Feature Requirements
Not every Axum extractor has the same feature gate setup. The Path extractor for URL parameters is always available - it is part of Axum's core with no separate feature flag. The Json extractor requires the json feature. The Form extractor requires the form feature. This means a project that uses Path and Query needs only the query feature for the extractor side, but a project that also handles JSON bodies needs both query and json.
The table below summarizes which extractor requires which feature:
| Extractor | Feature flag required | Always available? |
|---|---|---|
Path | None | Yes |
Query | "query" | Only with feature enabled |
Json | "json" | Only with feature enabled |
Form | "form" | Only with feature enabled |
When default-features are on, all four are available by default. When defaults are off, only Path remains without explicit opt-in.
Common Misunderstandings About the query Feature
There is a persistent confusion between the query feature and the Query extractor's runtime behavior. Some beginners believe that disabling the feature changes how query parameters are parsed, or that enabling it twice makes the extractor faster. The feature only controls compilation inclusion - it has zero effect on how the extractor behaves when it does exist.
Another frequent mistake is editing the wrong Cargo.toml. Rust projects sometimes have a workspace root with a [workspace] section and member crates, each with their own Cargo.toml. The Axum dependency declaration must appear in the Cargo.toml file of the crate that actually contains your handlers. If you add the feature to the workspace root but your handler lives in a member crate that does not declare Axum at all, the feature has no effect.
Editing the wrong Cargo.toml file:
In a multi-crate workspace, every crate that uses Axum must declare its own dependency with its own feature list. Adding features = ["query"] to the root Cargo.toml does not automatically apply to member crates. Check which file imports axum in your source code and edit that file.
Migrating from Axum 0.7 to 0.8 with Feature Flags
Axum 0.8 introduced changes to the default feature set compared to 0.7. If you are upgrading an existing project, run cargo tree -e features -p axum after the version bump to verify that query is still active. The default features in 0.8 are generally a superset of what most projects used in 0.7, but the only way to know for certain is to inspect the resolved feature set.
The migration process is simple: update the version number, run cargo build, and read any errors. If the compiler reports a missing Query type, add "query" to your feature list. If the compiler reports that it cannot find serve, add "tokio" and "http1". The errors are specific and guide you directly to the fix.
Summary
The query feature flag is a compile-time switch that determines whether Axum's Query extractor exists in your program. With default features enabled, it is always there and you can use it freely. When you disable default features - for smaller binaries or stricter control - you must list "query" explicitly alongside "tokio", "http1", and any other extractor features your handlers require. The compiler is your safety net: if the feature is missing, your import fails immediately with a clear "could not find type" error before any requests are served.
The single most important habit from this page is to run cargo tree -e features -p axum whenever feature behavior seems wrong. That command shows the resolved feature set and resolves confusion faster than any amount of guessing.