pub struct App { /* private fields */ }Expand description
A configured web application.
The App holds all routes, middleware, state, and lifecycle hooks,
and provides methods to handle incoming requests.
Implementations§
Source§impl App
impl App
Sourcepub fn builder() -> AppBuilder<()>
pub fn builder() -> AppBuilder<()>
Creates a new application builder.
Sourcepub fn route_count(&self) -> usize
pub fn route_count(&self) -> usize
Returns the number of registered routes.
Sourcepub fn state(&self) -> &Arc<RwLock<StateContainer>> ⓘ
pub fn state(&self) -> &Arc<RwLock<StateContainer>> ⓘ
Returns the shared state container (protected by RwLock for lifespan mutation).
Sourcepub fn get_state<T: Send + Sync + 'static>(&self) -> Option<Arc<T>>
pub fn get_state<T: Send + Sync + 'static>(&self) -> Option<Arc<T>>
Gets a reference to shared state of type T.
Sourcepub fn dependency_overrides(&self) -> &Arc<DependencyOverrides>
pub fn dependency_overrides(&self) -> &Arc<DependencyOverrides>
Returns the dependency overrides registry.
Sourcepub fn override_dependency<T, F, Fut>(&self, f: F)where
T: FromDependency,
F: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<T, T::Error>> + Send + 'static,
pub fn override_dependency<T, F, Fut>(&self, f: F)where
T: FromDependency,
F: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<T, T::Error>> + Send + 'static,
Registers a dependency override for this application (useful in tests).
Sourcepub fn override_dependency_value<T>(&self, value: T)where
T: FromDependency,
pub fn override_dependency_value<T>(&self, value: T)where
T: FromDependency,
Registers a fixed dependency override value.
Sourcepub fn clear_dependency_overrides(&self)
pub fn clear_dependency_overrides(&self)
Clears all registered dependency overrides.
Sourcepub fn exception_handlers(&self) -> &Arc<ExceptionHandlers>
pub fn exception_handlers(&self) -> &Arc<ExceptionHandlers>
Returns the exception handlers registry.
Sourcepub fn handle_error<E>(&self, ctx: &RequestContext, err: E) -> Option<Response>
pub fn handle_error<E>(&self, ctx: &RequestContext, err: E) -> Option<Response>
Handles an error using registered exception handlers.
If a handler is registered for the error type, it will be invoked.
Otherwise, returns None.
Sourcepub fn handle_error_or_default<E>(
&self,
ctx: &RequestContext,
err: E,
) -> Response
pub fn handle_error_or_default<E>( &self, ctx: &RequestContext, err: E, ) -> Response
Handles an error, returning a 500 response if no handler is registered.
Sourcepub fn mounted_apps(&self) -> &[MountedApp]
pub fn mounted_apps(&self) -> &[MountedApp]
Returns the mounted sub-applications.
Sourcepub async fn handle(&self, ctx: &RequestContext, req: &mut Request) -> Response
pub async fn handle(&self, ctx: &RequestContext, req: &mut Request) -> Response
Handles an incoming request.
This first checks mounted sub-applications (in registration order),
then matches against registered routes, runs middleware, and returns
the response. Path parameters are extracted and stored in request
extensions for use by the Path extractor.
§Mounted App Handling
When a request path matches a mounted app’s prefix, the request is forwarded to that app with the prefix stripped from the path. The mounted app’s middleware runs instead of the parent’s middleware.
§Special Parameter Injection
- ResponseMutations: Headers and cookies set by handlers are automatically applied to the final response.
- BackgroundTasks: Tasks are stored in request extensions via
BackgroundTasksInner. The HTTP server should retrieve and execute these after sending the response usingtake_background_tasks().
Sourcepub fn take_background_tasks(req: &mut Request) -> Option<BackgroundTasks>
pub fn take_background_tasks(req: &mut Request) -> Option<BackgroundTasks>
Take background tasks from a request after handling.
This should be called by the HTTP server after handle() returns
and the response has been sent to the client. The returned tasks
should be executed asynchronously.
§Example
let response = app.handle(&ctx, &mut request).await;
// Send response to client...
if let Some(tasks) = App::take_background_tasks(&mut request) {
tasks.execute_all().await;
}Sourcepub async fn run_startup_hooks(&self) -> StartupOutcome
pub async fn run_startup_hooks(&self) -> StartupOutcome
Runs all startup hooks.
Hooks run in registration order (FIFO). If a hook returns an error
with abort: true, execution stops and returns StartupOutcome::Aborted.
This consumes the startup hooks - they can only be run once.
§Returns
StartupOutcome::Successif all hooks succeededStartupOutcome::PartialSuccessif some hooks had non-fatal errorsStartupOutcome::Abortedif a fatal hook error occurred
Sourcepub async fn run_shutdown_hooks(&self)
pub async fn run_shutdown_hooks(&self)
Runs all shutdown hooks.
Hooks run in reverse registration order (LIFO). Errors are logged but do not stop other hooks from running.
This consumes the shutdown hooks - they can only be run once.
Sourcepub fn transfer_shutdown_hooks(&self, controller: &ShutdownController)
pub fn transfer_shutdown_hooks(&self, controller: &ShutdownController)
Transfers shutdown hooks to a ShutdownController.
This moves all registered shutdown hooks to the controller, which will run them during the appropriate shutdown phase.
Call this when integrating with the server’s shutdown mechanism.
Sourcepub fn pending_startup_hooks(&self) -> usize
pub fn pending_startup_hooks(&self) -> usize
Returns the number of pending startup hooks.
Sourcepub fn pending_shutdown_hooks(&self) -> usize
pub fn pending_shutdown_hooks(&self) -> usize
Returns the number of pending shutdown hooks.
Sourcepub fn test_client(self: Arc<Self>) -> TestClient<Arc<App>>
pub fn test_client(self: Arc<Self>) -> TestClient<Arc<App>>
Creates a crate::TestClient for this application.
The test client provides in-process testing without network overhead, simulating HTTP requests against the full application stack including middleware, routing, and handlers.
§Example
use fastapi_core::{App, Request, Response, RequestContext, Method};
async fn hello(ctx: &RequestContext, req: &mut Request) -> Response {
Response::ok().body_text("Hello!")
}
let app = App::builder()
.route("/hello", Method::Get, hello)
.build();
// Create test client from app
let client = app.test_client();
// Make requests
let response = client.get("/hello").send();
assert_eq!(response.status().as_u16(), 200);
assert_eq!(response.text(), "Hello!");Sourcepub fn test_client_with_seed(self: Arc<Self>, seed: u64) -> TestClient<Arc<App>>
pub fn test_client_with_seed(self: Arc<Self>, seed: u64) -> TestClient<Arc<App>>
Creates a crate::TestClient with a specific seed for deterministic testing.
Using the same seed produces reproducible behavior for tests involving concurrent operations or random elements.
§Example
let app = Arc::new(App::builder().build());
let client = app.test_client_with_seed(42);
// Tests will be deterministic with this seed