Skip to main content

AppBuilder

Struct AppBuilder 

Source
pub struct AppBuilder { /* private fields */ }
Expand description

Builder for constructing an App.

Use this to configure routes, middleware, and shared state before building the final application.

§Example

let app = App::builder()
    .config(AppConfig::new().name("My API"))
    .state(DatabasePool::new())
    .middleware(LoggingMiddleware::new())
    .on_startup(|| {
        println!("Server starting...");
        Ok(())
    })
    .on_shutdown(|| {
        println!("Server stopping...");
    })
    .route("/", Method::Get, index_handler)
    .route("/items", Method::Get, list_items)
    .route("/items", Method::Post, create_item)
    .route("/items/{id}", Method::Get, get_item)
    .build();

Implementations§

Source§

impl AppBuilder

Source

pub fn new() -> Self

Creates a new application builder.

Source

pub fn config(self, config: AppConfig) -> Self

Sets the application configuration.

Source

pub fn openapi(self, config: OpenApiConfig) -> Self

Enables and configures OpenAPI documentation.

When enabled, the application will automatically generate an OpenAPI 3.1 specification and serve it at the configured endpoint.

§Example
let app = App::builder()
    .openapi(OpenApiConfig::new()
        .title("My API")
        .version("1.0.0")
        .description("A sample API"))
    .build();
Source

pub fn enable_docs(self, config: DocsConfig) -> Self

Enables and configures interactive API documentation endpoints.

This wires crate::docs::DocsConfig into the application build and ensures an OpenAPI JSON endpoint is served at config.openapi_path unless overridden later.

Notes:

  • Docs endpoints are appended during build() so they don’t appear in the OpenAPI spec.
  • If OpenAPI is already configured, its openapi_path is updated to match DocsConfig.
Source

pub fn route<H, Fut>( self, path: impl Into<String>, method: Method, handler: H, ) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a route to the application.

Routes are matched in the order they are added.

Source

pub fn route_entry(self, entry: RouteEntry) -> Self

Adds a pre-built RouteEntry to the application.

This is primarily used by proc-macro generated route builders that already know the method/path and can build an extraction wrapper.

Source

pub fn websocket<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request, WebSocket) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), WebSocketError>> + Send + 'static,

Adds a websocket route to the application.

WebSocket routes are matched only when the server receives a valid websocket upgrade request. They do not appear in OpenAPI output.

Source

pub fn get<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a GET route.

Source

pub fn post<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a POST route.

Source

pub fn put<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a PUT route.

Source

pub fn delete<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a DELETE route.

Source

pub fn patch<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a PATCH route.

Source

pub fn middleware<M: Middleware + 'static>(self, middleware: M) -> Self

Adds middleware to the application.

Middleware is executed in the order it is added:

  • before hooks run first-to-last
  • after hooks run last-to-first
Source

pub fn state<T: Send + Sync + 'static>(self, state: T) -> Self

Adds shared state to the application.

State can be accessed by handlers through the State<T> extractor.

Source

pub fn exception_handler<E, H>(self, handler: H) -> Self
where E: Error + Send + Sync + 'static, H: Fn(&RequestContext, E) -> Response + Send + Sync + 'static,

Registers a custom exception handler for a specific error type.

When an error of type E occurs during request handling, the registered handler will be called to convert it into a response.

§Example
#[derive(Debug)]
struct AuthError(String);

impl std::fmt::Display for AuthError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Auth error: {}", self.0)
    }
}

impl std::error::Error for AuthError {}

let app = App::builder()
    .exception_handler(|_ctx, err: AuthError| {
        Response::with_status(StatusCode::UNAUTHORIZED)
            .header("www-authenticate", b"Bearer".to_vec())
            .body_json(&json!({"error": err.0}))
    })
    .build();
Source

pub fn exception_handlers(self, handlers: ExceptionHandlers) -> Self

Sets the exception handlers registry.

This replaces any previously registered handlers.

Source

pub fn with_default_exception_handlers(self) -> Self

Uses default exception handlers for common error types.

This registers handlers for:

Source

pub fn on_startup<F>(self, hook: F) -> Self
where F: FnOnce() -> Result<(), StartupHookError> + Send + 'static,

Registers a synchronous startup hook.

Startup hooks run before the server starts accepting connections, in the order they are registered (FIFO).

§Example
let app = App::builder()
    .on_startup(|| {
        println!("Connecting to database...");
        Ok(())
    })
    .on_startup(|| {
        println!("Loading configuration...");
        Ok(())
    })
    .build();
Source

pub fn on_startup_async<F, Fut>(self, hook: F) -> Self
where F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = Result<(), StartupHookError>> + Send + 'static,

Registers an async startup hook.

Async startup hooks are awaited in registration order.

§Example
let app = App::builder()
    .on_startup_async(|| async {
        let pool = connect_to_database().await?;
        Ok(())
    })
    .build();
Source

pub fn on_shutdown<F>(self, hook: F) -> Self
where F: FnOnce() + Send + 'static,

Registers a synchronous shutdown hook.

Shutdown hooks run after the server stops accepting connections and all in-flight requests complete (or are cancelled).

Shutdown hooks run in reverse registration order (LIFO), matching typical resource cleanup patterns (last acquired, first released).

§Example
let app = App::builder()
    .on_shutdown(|| {
        println!("Closing database connections...");
    })
    .build();
Source

pub fn on_shutdown_async<F, Fut>(self, hook: F) -> Self
where F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = ()> + Send + 'static,

Registers an async shutdown hook.

Async shutdown hooks are awaited in reverse registration order (LIFO).

§Example
let app = App::builder()
    .on_shutdown_async(|| async {
        flush_metrics().await;
    })
    .build();
Source

pub fn startup_hook_count(&self) -> usize

Returns the number of registered startup hooks.

Source

pub fn shutdown_hook_count(&self) -> usize

Returns the number of registered shutdown hooks.

Source

pub fn build(self) -> App

Builds the application.

This consumes the builder and returns the configured App.

§Panics

Panics if any routes conflict (same method + structurally identical path pattern).

Trait Implementations§

Source§

impl Debug for AppBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for AppBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ResponseProduces<T> for T