Skip to main content

axum/
lib.rs

1//! axum is an HTTP routing and request-handling library that focuses on ergonomics and modularity.
2//!
3//! # High-level features
4//!
5//! - Route requests to handlers with a macro-free API.
6//! - Declaratively parse requests using extractors.
7//! - Simple and predictable error handling model.
8//! - Generate responses with minimal boilerplate.
9//! - Take full advantage of the [`tower`] and [`tower-http`] ecosystem of
10//!   middleware, services, and utilities.
11//!
12//! In particular, the last point is what sets `axum` apart from other libraries / frameworks.
13//! `axum` doesn't have its own middleware system but instead uses
14//! [`tower::Service`]. This means `axum` gets timeouts, tracing, compression,
15//! authorization, and more, for free. It also enables you to share middleware with
16//! applications written using [`hyper`] or [`tonic`].
17//!
18//! # Compatibility
19//!
20//! axum is designed to work with [tokio] and [hyper]. Runtime and
21//! transport layer independence is not a goal, at least for the time being.
22//!
23//! # Example
24//!
25//! The "Hello, World!" of axum is:
26//!
27//! ```rust,no_run
28//! use axum::{
29//!     routing::get,
30//!     Router,
31//! };
32//!
33//! #[tokio::main]
34//! async fn main() {
35//!     // build our application with a single route
36//!     let app = Router::new().route("/", get(|| async { "Hello, World!" }));
37//!
38//!     // run our app with hyper, listening globally on port 3000
39//!     let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
40//!     axum::serve(listener, app).await;
41//! }
42//! ```
43//!
44//! Note using `#[tokio::main]` requires you enable tokio's `macros` and `rt-multi-thread` features
45//! or just `full` to enable all features (`cargo add tokio --features macros,rt-multi-thread`).
46//!
47//! # Routing
48//!
49//! [`Router`] is used to set up which paths go to which services:
50//!
51//! ```rust
52//! use axum::{Router, routing::get};
53//!
54//! // our router
55//! let app = Router::new()
56//!     .route("/", get(root))
57//!     .route("/foo", get(get_foo).post(post_foo))
58//!     .route("/foo/bar", get(foo_bar));
59//!
60//! // which calls one of these handlers
61//! async fn root() {}
62//! async fn get_foo() {}
63//! async fn post_foo() {}
64//! async fn foo_bar() {}
65//! # let _: Router = app;
66//! ```
67//!
68//! See [`Router`] for more details on routing.
69//!
70//! # Handlers
71//!
72#![doc = include_str!("docs/handlers_intro.md")]
73//!
74//! See [`handler`] for more details on handlers.
75//!
76//! # Extractors
77//!
78//! An extractor is a type that implements [`FromRequest`] or [`FromRequestParts`]. Extractors are
79//! how you pick apart the incoming request to get the parts your handler needs.
80//!
81//! ```rust
82//! use axum::extract::{Path, Query, Json};
83//! use std::collections::HashMap;
84//!
85//! // `Path` gives you the path parameters and deserializes them.
86//! async fn path(Path(user_id): Path<u32>) {}
87//!
88//! // `Query` gives you the query parameters and deserializes them.
89//! async fn query(Query(params): Query<HashMap<String, String>>) {}
90//!
91//! // Buffer the request body and deserialize it as JSON into a
92//! // `serde_json::Value`. `Json` supports any type that implements
93//! // `serde::Deserialize`.
94//! async fn json(Json(payload): Json<serde_json::Value>) {}
95//! ```
96//!
97//! See [`extract`] for more details on extractors.
98//!
99//! # Responses
100//!
101//! Anything that implements [`IntoResponse`] can be returned from handlers.
102//!
103//! ```rust,no_run
104//! use axum::{
105//!     body::Body,
106//!     routing::get,
107//!     response::Json,
108//!     Router,
109//! };
110//! use serde_json::{Value, json};
111//!
112//! // `&'static str` becomes a `200 OK` with `content-type: text/plain; charset=utf-8`
113//! async fn plain_text() -> &'static str {
114//!     "foo"
115//! }
116//!
117//! // `Json` gives a content-type of `application/json` and works with any type
118//! // that implements `serde::Serialize`
119//! async fn json() -> Json<Value> {
120//!     Json(json!({ "data": 42 }))
121//! }
122//!
123//! let app = Router::new()
124//!     .route("/plain_text", get(plain_text))
125//!     .route("/json", get(json));
126//! # let _: Router = app;
127//! ```
128//!
129//! See [`response`] for more details on building responses.
130//!
131//! # Error handling
132//!
133//! axum aims to have a simple and predictable error handling model. That means
134//! it is simple to convert errors into responses and you are guaranteed that
135//! all errors are handled.
136//!
137//! See [`error_handling`] for more details on axum's
138//! error handling model and how to handle errors gracefully.
139//!
140//! # Middleware
141//!
142//! There are several different ways to write middleware for axum. See
143//! [`middleware`] for more details.
144//!
145//! # Sharing state with handlers
146//!
147//! It is common to share some state between handlers. For example, a
148//! pool of database connections or clients to other services may need to
149//! be shared.
150//!
151//! The four most common ways of doing that are:
152//!
153//! - Using the [`State`] extractor
154//! - Using request extensions
155//! - Using closure captures
156//! - Using task-local variables
157//!
158//! ## Using the [`State`] extractor
159//!
160//! ```rust,no_run
161//! use axum::{
162//!     extract::State,
163//!     routing::get,
164//!     Router,
165//! };
166//! use std::sync::Arc;
167//!
168//! struct AppState {
169//!     // ...
170//! }
171//!
172//! let shared_state = Arc::new(AppState { /* ... */ });
173//!
174//! let app = Router::new()
175//!     .route("/", get(handler))
176//!     .with_state(shared_state);
177//!
178//! async fn handler(
179//!     State(state): State<Arc<AppState>>,
180//! ) {
181//!     // ...
182//! }
183//! # let _: Router = app;
184//! ```
185//!
186//! State is cloned for every request. Wrapping your state in `Arc` makes those
187//! clones cheap. If all fields are already cheap to clone (for example, each field
188//! is itself an `Arc` or a copy type), you can `#[derive(Clone)]` directly on the
189//! struct instead. Many client types, such as [`reqwest::Client`], AWS SDK service
190//! clients, and [`mongodb::Client`], already use shared ownership internally and
191//! are cheap to clone. Such clients generally do not need another `Arc` solely to
192//! make cloning cheap; doing so adds another level of indirection.
193//!
194//! [`reqwest::Client`]: https://docs.rs/reqwest/latest/reqwest/struct.Client.html
195//! [`mongodb::Client`]: https://docs.rs/mongodb/latest/mongodb/struct.Client.html
196//!
197//! ### Using `&'static` state
198//!
199//! For state built once and intended to live until the process exits, [`Box::leak`]
200//! or a static [`LazyLock`] can provide a `&'static AppState` to the router. Use
201//! `Box::leak` for state initialized in `main`, including when state initialization
202//! requires asynchronous work; use a static `LazyLock` for global state with a
203//! synchronous lazy initializer. This is useful for state built from runtime
204//! configuration, database pools, or service clients:
205//!
206//! ```rust
207//! use axum::{
208//!     extract::State,
209//!     routing::get,
210//!     Router,
211//! };
212//!
213//! struct AppState {
214//!     // A database pool, service clients, configuration, etc.
215//! }
216//!
217//! impl AppState {
218//!     async fn work(&self) {}
219//! }
220//!
221//! fn main() {
222//!     let app_state = AppState {
223//!         // Initialize fields at startup.
224//!     };
225//!     let app_state: &'static AppState = Box::leak(Box::new(app_state));
226//!
227//!     let app = Router::new()
228//!         .route("/", get(handler))
229//!         .with_state(app_state);
230//!     # let _: Router = app;
231//! }
232//!
233//! async fn handler(State(state): State<&'static AppState>) {
234//!     let _task = tokio::spawn(async move {
235//!         state.work().await;
236//!     });
237//!
238//!     // `state` is still available in the handler because it was copied.
239//!     state.work().await;
240//! }
241//! ```
242//!
243//! Like every shared reference, a `&'static T` is `Copy`, so axum can clone it for
244//! each request without an atomic reference-count operation. This can be cheaper than
245//! cloning an `Arc`, but it is rarely a reason on its own to choose process-lifetime
246//! state since the request's actual work normally matters more. The more practical
247//! advantage of combining `Copy` with the `'static` lifetime is shown above: an
248//! `async move` block copies the reference into the spawned Tokio task while leaving
249//! the handler's copy available. With `Arc`, call [`Arc::clone`] before spawning when
250//! the handler also needs the state.
251//!
252//! `Box::leak` deliberately leaks its allocation, and state held by a static
253//! `LazyLock` is likewise never dropped. Use either only for process-lifetime state.
254//! Use `Arc` when the state needs a managed lifetime.
255//!
256//! [`Arc::clone`]: https://doc.rust-lang.org/std/sync/struct.Arc.html#method.clone
257//! [`Box::leak`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.leak
258//! [`LazyLock`]: https://doc.rust-lang.org/std/sync/struct.LazyLock.html
259//!
260//! ### Substates with `FromRef`
261//!
262//! When a handler only needs part of the application state, use [`FromRef`] to extract
263//! a substate. Implement the trait manually, or derive it with `#[derive(FromRef)]`
264//! (requires the `macros` feature):
265//!
266//! ```rust
267//! use axum::{Router, routing::get, extract::{State, FromRef}};
268//!
269//! #[derive(Clone)]
270//! struct AppState {
271//!     api_state: ApiState,
272//! }
273//!
274//! #[derive(Clone)]
275//! struct ApiState {}
276//!
277//! // Teach axum how to produce an `ApiState` from a reference to `AppState`.
278//! impl FromRef<AppState> for ApiState {
279//!     fn from_ref(app_state: &AppState) -> ApiState {
280//!         app_state.api_state.clone()
281//!     }
282//! }
283//!
284//! let app = Router::new()
285//!     .route("/", get(handler))
286//!     .with_state(AppState { api_state: ApiState {} });
287//!
288//! // This handler receives only the `ApiState` slice; it never sees `AppState`.
289//! async fn handler(State(api_state): State<ApiState>) {}
290//! # let _: Router = app;
291//! ```
292//!
293//! ### The `Router<S>` type parameter
294//!
295//! `Router<S>` when `S` is not `()` means a router that is _missing_ a state of type `S`. Calling
296//! [`.with_state(s)`][Router::with_state] provides that state and typically produces a
297//! `Router<()>`, which is the only form that can be passed to [`serve()`]. See
298//! [`Router::with_state`] for a full explanation.
299//!
300//! You should prefer using [`State`] if possible since it's more type safe. The downside is that
301//! it's less dynamic than task-local variables and request extensions.
302//!
303//! See [`State`] for more details about accessing state.
304//!
305//! ## Using request extensions
306//!
307//! Another way to share state with handlers is using [`Extension`] as
308//! layer and extractor:
309//!
310//! ```rust,no_run
311//! use axum::{
312//!     extract::Extension,
313//!     routing::get,
314//!     Router,
315//! };
316//! use std::sync::Arc;
317//!
318//! struct AppState {
319//!     // ...
320//! }
321//!
322//! let shared_state = Arc::new(AppState { /* ... */ });
323//!
324//! let app = Router::new()
325//!     .route("/", get(handler))
326//!     .layer(Extension(shared_state));
327//!
328//! async fn handler(
329//!     Extension(state): Extension<Arc<AppState>>,
330//! ) {
331//!     // ...
332//! }
333//! # let _: Router = app;
334//! ```
335//!
336//! The downside to this approach is that you'll get runtime errors
337//! (specifically a `500 Internal Server Error` response) if you try and extract
338//! an extension that doesn't exist, perhaps because you forgot to add the
339//! middleware or because you're extracting the wrong type.
340//!
341//! ## Using closure captures
342//!
343//! State can also be passed directly to handlers using closure captures:
344//!
345//! ```rust,no_run
346//! use axum::{
347//!     Json,
348//!     extract::{Extension, Path},
349//!     routing::{get, post},
350//!     Router,
351//! };
352//! use std::sync::Arc;
353//! use serde::Deserialize;
354//!
355//! struct AppState {
356//!     // ...
357//! }
358//!
359//! let shared_state = Arc::new(AppState { /* ... */ });
360//!
361//! let app = Router::new()
362//!     .route(
363//!         "/users",
364//!         post({
365//!             let shared_state = Arc::clone(&shared_state);
366//!             move |body| create_user(body, shared_state)
367//!         }),
368//!     )
369//!     .route(
370//!         "/users/{id}",
371//!         get({
372//!             let shared_state = Arc::clone(&shared_state);
373//!             move |path| get_user(path, shared_state)
374//!         }),
375//!     );
376//!
377//! async fn get_user(Path(user_id): Path<String>, state: Arc<AppState>) {
378//!     // ...
379//! }
380//!
381//! async fn create_user(Json(payload): Json<CreateUserPayload>, state: Arc<AppState>) {
382//!     // ...
383//! }
384//!
385//! #[derive(Deserialize)]
386//! struct CreateUserPayload {
387//!     // ...
388//! }
389//! # let _: Router = app;
390//! ```
391//!
392//! The downside to this approach is that it's the most verbose approach.
393//!
394//! ## Using task-local variables
395//!
396//! This also allows sharing state with `IntoResponse` implementations:
397//!
398//! ```rust,no_run
399//! use axum::{
400//!     extract::Request,
401//!     http::{header, StatusCode},
402//!     middleware::{self, Next},
403//!     response::{IntoResponse, Response},
404//!     routing::get,
405//!     Router,
406//! };
407//! use tokio::task_local;
408//!
409//! #[derive(Clone)]
410//! struct CurrentUser {
411//!     name: String,
412//! }
413//! task_local! {
414//!     pub static USER: CurrentUser;
415//! }
416//!
417//! async fn auth(req: Request, next: Next) -> Result<Response, StatusCode> {
418//!     let auth_header = req
419//!         .headers()
420//!         .get(header::AUTHORIZATION)
421//!         .and_then(|header| header.to_str().ok())
422//!         .ok_or(StatusCode::UNAUTHORIZED)?;
423//!     if let Some(current_user) = authorize_current_user(auth_header).await {
424//!         // State is set up here in the middleware
425//!         Ok(USER.scope(current_user, next.run(req)).await)
426//!     } else {
427//!         Err(StatusCode::UNAUTHORIZED)
428//!     }
429//! }
430//! async fn authorize_current_user(auth_token: &str) -> Option<CurrentUser> {
431//!     Some(CurrentUser {
432//!         name: auth_token.to_string(),
433//!     })
434//! }
435//!
436//! struct UserResponse;
437//!
438//! impl IntoResponse for UserResponse {
439//!     fn into_response(self) -> Response {
440//!         // State is accessed here in the IntoResponse implementation
441//!         let current_user = USER.with(|u| u.clone());
442//!         (StatusCode::OK, current_user.name).into_response()
443//!     }
444//! }
445//!
446//! async fn handler() -> UserResponse {
447//!     UserResponse
448//! }
449//!
450//! let app: Router = Router::new()
451//!     .route("/", get(handler))
452//!     .route_layer(middleware::from_fn(auth));
453//! ```
454//!
455//! The main downside to this approach is that it only works when the async executor being used
456//! has the concept of task-local variables. The example above uses
457//! [tokio's `task_local` macro](https://docs.rs/tokio/1/tokio/macro.task_local.html).
458//! smol does not yet offer equivalent functionality at the time of writing (see
459//! [this GitHub issue](https://github.com/smol-rs/async-executor/issues/139)).
460//!
461//! # Building integrations for axum
462//!
463//! Libraries authors that want to provide [`FromRequest`], [`FromRequestParts`], or
464//! [`IntoResponse`] implementations should depend on the [`axum-core`] crate, instead of `axum` if
465//! possible. [`axum-core`] contains core types and traits and is less likely to receive breaking
466//! changes.
467//!
468//! # Required dependencies
469//!
470//! To use axum there are a few dependencies you have to pull in as well:
471//!
472//! ```toml
473//! [dependencies]
474//! axum = "<latest-version>"
475//! tokio = { version = "<latest-version>", features = ["full"] }
476//! tower = "<latest-version>"
477//! ```
478//!
479//! The `"full"` feature for tokio isn't necessary but it's the easiest way to get started.
480//!
481//! Tower isn't strictly necessary either but helpful for testing. See the
482//! testing example in the repo to learn more about testing axum apps.
483//!
484//! # Examples
485//!
486//! The axum repo contains [a number of examples][examples] that show how to put all the
487//! pieces together.
488//!
489//! # Feature flags
490//!
491//! axum uses a set of [feature flags] to reduce the amount of compiled and
492//! optional dependencies.
493//!
494//! The following optional features are available:
495//!
496//! Name | Description | Default?
497//! ---|---|---
498//! `http1` | Enables hyper's `http1` feature | <span role="img" aria-label="Default feature">✔</span>
499//! `http2` | Enables hyper's `http2` feature |
500//! `json` | Enables the [`Json`] type and some similar convenience functionality | <span role="img" aria-label="Default feature">✔</span>
501//! `macros` | Enables optional utility macros |
502//! `matched-path` | Enables capturing of every request's router path and the [`MatchedPath`] extractor | <span role="img" aria-label="Default feature">✔</span>
503//! `multipart` | Enables parsing `multipart/form-data` requests with [`Multipart`] |
504//! `original-uri` | Enables capturing of every request's original URI and the [`OriginalUri`] extractor | <span role="img" aria-label="Default feature">✔</span>
505//! `tokio` | Enables `tokio` as a dependency and `axum::serve`, `SSE` and `extract::connect_info` types. | <span role="img" aria-label="Default feature">✔</span>
506//! `tower-log` | Enables `tower`'s `log` feature |
507//! `tracing` | Log rejections from built-in extractors | <span role="img" aria-label="Default feature">✔</span>
508//! `ws` | Enables WebSockets support via [`extract::ws`] |
509//! `form` | Enables the `Form` extractor | <span role="img" aria-label="Default feature">✔</span>
510//! `query` | Enables the `Query` extractor | <span role="img" aria-label="Default feature">✔</span>
511//!
512//! [`MatchedPath`]: crate::extract::MatchedPath
513//! [`Multipart`]: crate::extract::Multipart
514//! [`OriginalUri`]: crate::extract::OriginalUri
515//! [`tower`]: https://crates.io/crates/tower
516//! [`tower-http`]: https://crates.io/crates/tower-http
517//! [`tokio`]: http://crates.io/crates/tokio
518//! [`hyper`]: http://crates.io/crates/hyper
519//! [`tonic`]: http://crates.io/crates/tonic
520//! [feature flags]: https://doc.rust-lang.org/cargo/reference/features.html#the-features-section
521//! [`IntoResponse`]: crate::response::IntoResponse
522//! [`Timeout`]: tower::timeout::Timeout
523//! [examples]: https://github.com/tokio-rs/axum/tree/main/examples
524//! [`Router::merge`]: crate::routing::Router::merge
525//! [`Service`]: tower::Service
526//! [`Service::poll_ready`]: tower::Service::poll_ready
527//! [`Service`'s]: tower::Service
528//! [`tower::Service`]: tower::Service
529//! [tower-guides]: https://github.com/tower-rs/tower/tree/master/guides
530//! [`Uuid`]: https://docs.rs/uuid/latest/uuid/
531//! [`FromRequest`]: crate::extract::FromRequest
532//! [`FromRequestParts`]: crate::extract::FromRequestParts
533//! [`HeaderMap`]: http::header::HeaderMap
534//! [`Request`]: http::Request
535//! [customize-extractor-error]: https://github.com/tokio-rs/axum/blob/main/examples/customize-extractor-error/src/main.rs
536//! [axum-macros]: https://docs.rs/axum-macros
537//! [`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html
538//! [`Handler`]: crate::handler::Handler
539//! [`Infallible`]: std::convert::Infallible
540//! [load shed]: tower::load_shed
541//! [`axum-core`]: http://crates.io/crates/axum-core
542//! [`State`]: crate::extract::State
543//! [`FromRef`]: crate::extract::FromRef
544//! [`Router::with_state`]: crate::routing::Router::with_state
545
546#![cfg_attr(docsrs, feature(doc_cfg))]
547#![cfg_attr(test, allow(clippy::float_cmp))]
548#![cfg_attr(not(test), warn(clippy::print_stdout, clippy::dbg_macro))]
549
550#[macro_use]
551pub(crate) mod macros;
552
553mod boxed;
554mod extension;
555#[cfg(feature = "form")]
556mod form;
557#[cfg(feature = "json")]
558mod json;
559mod service_ext;
560mod util;
561
562pub mod body;
563pub mod error_handling;
564pub mod extract;
565pub mod handler;
566pub mod middleware;
567pub mod response;
568pub mod routing;
569#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
570pub mod serve;
571
572#[cfg(any(test, feature = "__private"))]
573#[allow(missing_docs, missing_debug_implementations, clippy::print_stdout)]
574#[doc(hidden)]
575pub mod test_helpers;
576
577#[doc(no_inline)]
578pub use http;
579
580#[doc(inline)]
581pub use self::extension::Extension;
582#[doc(inline)]
583#[cfg(feature = "json")]
584pub use self::json::Json;
585#[doc(inline)]
586pub use self::routing::Router;
587
588#[doc(inline)]
589#[cfg(feature = "form")]
590pub use self::form::Form;
591
592#[doc(inline)]
593pub use axum_core::{BoxError, Error, RequestExt, RequestPartsExt};
594
595#[cfg(feature = "macros")]
596pub use axum_macros::{debug_handler, debug_middleware};
597
598#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
599#[doc(inline)]
600pub use self::serve::serve;
601
602pub use self::service_ext::ServiceExt;
603
604#[cfg(test)]
605use axum_macros::__private_axum_test as test;