Skip to main content

App

Struct App 

Source
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

Source

pub fn builder() -> AppBuilder<()>

Creates a new application builder.

Source

pub fn config(&self) -> &AppConfig

Returns the application configuration.

Source

pub fn route_count(&self) -> usize

Returns the number of registered routes.

Source

pub fn state(&self) -> &Arc<RwLock<StateContainer>>

Returns the shared state container (protected by RwLock for lifespan mutation).

Source

pub fn get_state<T: Send + Sync + 'static>(&self) -> Option<Arc<T>>

Gets a reference to shared state of type T.

Source

pub fn dependency_overrides(&self) -> &Arc<DependencyOverrides>

Returns the dependency overrides registry.

Source

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).

Source

pub fn override_dependency_value<T>(&self, value: T)
where T: FromDependency,

Registers a fixed dependency override value.

Source

pub fn clear_dependency_overrides(&self)

Clears all registered dependency overrides.

Source

pub fn exception_handlers(&self) -> &Arc<ExceptionHandlers>

Returns the exception handlers registry.

Source

pub fn handle_error<E>(&self, ctx: &RequestContext, err: E) -> Option<Response>
where E: Error + Send + Sync + 'static,

Handles an error using registered exception handlers.

If a handler is registered for the error type, it will be invoked. Otherwise, returns None.

Source

pub fn handle_error_or_default<E>( &self, ctx: &RequestContext, err: E, ) -> Response
where E: Error + Send + Sync + 'static,

Handles an error, returning a 500 response if no handler is registered.

Source

pub fn mounted_apps(&self) -> &[MountedApp]

Returns the mounted sub-applications.

Source

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 using take_background_tasks().
Source

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;
}
Source

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::Success if all hooks succeeded
  • StartupOutcome::PartialSuccess if some hooks had non-fatal errors
  • StartupOutcome::Aborted if a fatal hook error occurred
Source

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.

Source

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.

Source

pub fn pending_startup_hooks(&self) -> usize

Returns the number of pending startup hooks.

Source

pub fn pending_shutdown_hooks(&self) -> usize

Returns the number of pending shutdown hooks.

Source

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!");
Source

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

Trait Implementations§

Source§

impl Debug for App

Source§

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

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

impl Handler for App

Source§

fn call<'a>( &'a self, ctx: &'a RequestContext, req: &'a mut Request, ) -> BoxFuture<'a, Response>

Process a request and return a response.
Source§

fn dependency_overrides(&self) -> Option<Arc<DependencyOverrides>>

Optional dependency overrides to apply when building request contexts. Read more

Auto Trait Implementations§

§

impl !Freeze for App

§

impl !RefUnwindSafe for App

§

impl Send for App

§

impl Sync for App

§

impl Unpin for App

§

impl !UnwindSafe for App

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