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
impl AppBuilder
Sourcepub fn openapi(self, config: OpenApiConfig) -> Self
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();Sourcepub fn enable_docs(self, config: DocsConfig) -> Self
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_pathis updated to matchDocsConfig.
Sourcepub fn route<H, Fut>(
self,
path: impl Into<String>,
method: Method,
handler: H,
) -> Self
pub fn route<H, Fut>( self, path: impl Into<String>, method: Method, handler: H, ) -> Self
Adds a route to the application.
Routes are matched in the order they are added.
Sourcepub fn route_entry(self, entry: RouteEntry) -> Self
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.
Sourcepub fn websocket<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
pub fn websocket<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
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.
Sourcepub fn middleware<M: Middleware + 'static>(self, middleware: M) -> Self
pub fn middleware<M: Middleware + 'static>(self, middleware: M) -> Self
Adds middleware to the application.
Middleware is executed in the order it is added:
beforehooks run first-to-lastafterhooks run last-to-first
Sourcepub fn state<T: Send + Sync + 'static>(self, state: T) -> Self
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.
Sourcepub fn exception_handler<E, H>(self, handler: H) -> Self
pub fn exception_handler<E, H>(self, handler: H) -> Self
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();Sourcepub fn exception_handlers(self, handlers: ExceptionHandlers) -> Self
pub fn exception_handlers(self, handlers: ExceptionHandlers) -> Self
Sets the exception handlers registry.
This replaces any previously registered handlers.
Sourcepub fn with_default_exception_handlers(self) -> Self
pub fn with_default_exception_handlers(self) -> Self
Uses default exception handlers for common error types.
This registers handlers for:
HttpError→ JSON response with status/detailValidationErrors→ 422 with error list
Sourcepub fn on_startup<F>(self, hook: F) -> Self
pub fn on_startup<F>(self, hook: F) -> Self
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();Sourcepub fn on_startup_async<F, Fut>(self, hook: F) -> Self
pub fn on_startup_async<F, Fut>(self, hook: F) -> Self
Sourcepub fn on_shutdown<F>(self, hook: F) -> Self
pub fn on_shutdown<F>(self, hook: F) -> Self
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();Sourcepub fn on_shutdown_async<F, Fut>(self, hook: F) -> Self
pub fn on_shutdown_async<F, Fut>(self, hook: F) -> Self
Sourcepub fn startup_hook_count(&self) -> usize
pub fn startup_hook_count(&self) -> usize
Returns the number of registered startup hooks.
Sourcepub fn shutdown_hook_count(&self) -> usize
pub fn shutdown_hook_count(&self) -> usize
Returns the number of registered shutdown hooks.