Expand description
Core types and traits for fastapi_rust.
This crate provides the fundamental building blocks:
RequestandResponsetypesRequestContextwrapping asupersync’sCxFromRequesttrait for extractors- Error types and
IntoResponsetrait
§Design Principles
- Zero-copy where possible
- No runtime reflection
- All types support
Send + Sync - Cancel-correct via asupersync integration
§Asupersync Integration
This crate uses asupersync as its async runtime foundation, providing:
- Structured concurrency: Request handlers run in regions
- Cancel-correctness: Graceful cancellation via checkpoints
- Budgeted timeouts: Request timeouts via budget exhaustion
- Deterministic testing: Lab runtime for reproducible tests
Re-exports§
pub use digest::DigestAlgorithm;pub use digest::DigestAuth;pub use digest::DigestAuthError;pub use digest::DigestAuthErrorKind;pub use digest::DigestQop;pub use error::HttpError;pub use error::LocItem;pub use error::ValidationError;pub use error::ValidationErrors;pub use extract::Validate;pub use middleware::AddResponseHeader;pub use middleware::BoxFuture;pub use middleware::ControlFlow;pub use middleware::Cors;pub use middleware::CorsConfig;pub use middleware::Handler;pub use middleware::Layer;pub use middleware::Layered;pub use middleware::Middleware;pub use middleware::MiddlewareStack;pub use middleware::NoopMiddleware;pub use middleware::OriginPattern;pub use middleware::PathPrefixFilter;pub use middleware::ReferrerPolicy;pub use middleware::RequestId;pub use middleware::RequestIdConfig;pub use middleware::RequestIdMiddleware;pub use middleware::RequestResponseLogger;pub use middleware::RequireHeader;pub use middleware::SecurityHeaders;pub use middleware::SecurityHeadersConfig;pub use middleware::XFrameOptions;pub use multipart::DEFAULT_MAX_FIELDS;pub use multipart::DEFAULT_MAX_FILE_SIZE;pub use multipart::DEFAULT_MAX_TOTAL_SIZE;pub use multipart::MultipartConfig;pub use multipart::MultipartError;pub use multipart::MultipartForm;pub use multipart::MultipartParser;pub use multipart::Part;pub use multipart::UploadFile;pub use multipart::parse_boundary;pub use websocket::Frame as WebSocketFrame;pub use websocket::OpCode as WebSocketOpCode;pub use websocket::WS_GUID;pub use websocket::WebSocket;pub use websocket::WebSocketError;pub use websocket::WebSocketHandshakeError;pub use websocket::websocket_accept_from_key;pub use docs::DocsConfig;pub use docs::oauth2_redirect_html;pub use docs::oauth2_redirect_response;pub use docs::redoc_html;pub use docs::redoc_response;pub use docs::swagger_ui_html;pub use docs::swagger_ui_response;pub use testing::CookieJar;pub use testing::FixtureGuard;pub use testing::IntegrationTest;pub use testing::RequestBuilder;pub use testing::TestClient;pub use testing::TestFixture;pub use testing::TestResponse;pub use testing::json_contains;pub use logging::AutoSpan;pub use logging::LogConfig;pub use logging::LogEntry;pub use logging::LogLevel;pub use logging::Span;pub use app::App;pub use app::AppBuilder;pub use app::AppConfig;pub use app::ExceptionHandlers;pub use app::OpenApiConfig;pub use app::RouteEntry;pub use app::StartupHook;pub use app::StartupHookError;pub use app::StartupOutcome;pub use app::StateContainer;pub use shutdown::GracefulConfig;pub use shutdown::GracefulShutdown;pub use shutdown::InFlightGuard;pub use shutdown::ShutdownAware;pub use shutdown::ShutdownController;pub use shutdown::ShutdownHook;pub use shutdown::ShutdownOutcome;pub use shutdown::ShutdownPhase;pub use shutdown::ShutdownReceiver;pub use shutdown::grace_expired_cancel_reason;pub use shutdown::shutdown_cancel_reason;pub use shutdown::subdivide_grace_budget;
Modules§
- app
- Application builder and runtime for fastapi_rust.
- coverage
- Code coverage integration for fastapi_rust.
- digest
- HTTP Digest authentication (RFC 7616 / RFC 2617).
- docs
- Interactive API documentation endpoints.
- error
- Error types.
- logging
- Structured logging infrastructure for fastapi_rust.
- middleware
- Middleware abstraction for request/response processing.
- multipart
- Multipart form data parser.
- routing
- Path matching and routing utilities.
- shutdown
- Graceful shutdown coordination for the server.
- testing
- Test utilities for fastapi applications.
- validation
- Validation helper functions for the
#[derive(Validate)]macro. - websocket
- WebSocket protocol support (RFC 6455).
Macros§
- assert_
body_ contains - Asserts that a test response body contains the expected substring.
- assert_
eq_ with_ logs - Assertion helper that includes log context for equality checks.
- assert_
header - Asserts that a test response has a header with the expected value.
- assert_
json - Asserts that a test response body matches the expected JSON value (partial match).
- assert_
response_ snapshot - Macro for snapshot testing a response against a file fixture.
- assert_
status - Asserts that a test response has the expected HTTP status code.
- assert_
with_ logs - Assertion helper that includes log context on failure.
- debug_
location - Macro to capture the current source location for debug info.
- e2e_
test - Macro for defining E2E test scenarios with a declarative syntax.
- log_
debug - Logs a message at the DEBUG level with request context.
- log_
error - Logs a message at the ERROR level with request context.
- log_
info - Logs a message at the INFO level with request context.
- log_
trace - Logs a message at the TRACE level with request context.
- log_
warn - Logs a message at the WARN level with request context.
- record_
branch - Helper macro for recording branch coverage.
Structs§
- Accept
- Accept header marker.
- ApiKey
- API key authentication extractor.
- ApiKey
Config - Configuration for API key extraction.
- ApiKey
Error - Error when API key extraction fails.
- AppState
- Application state container.
- Authorization
- Authorization header marker.
- Background
Tasks - Basic
Auth - HTTP Basic Authentication credentials extractor.
- Basic
Auth Error - Error when HTTP Basic Auth extraction fails.
- Bearer
Token - Bearer token extractor for
Authorization: Bearer <token>. - Bearer
Token Error - Error when bearer token extraction fails.
- Binary
- Binary response with
application/octet-streamcontent type. - Budget
- A budget constraining resource usage for a task or region.
- Cancelled
Error - Error returned when a request has been cancelled.
- Content
Type - Content-Type header marker.
- Cookie
- Cookie value extractor.
- Cookie
Extract Error - Error when cookie extraction fails.
- Csrf
Token - CSRF token cookie marker.
- Csrf
Token Cookie - CSRF token cookie marker (compat alias used by some middleware/tests).
- Cx
- The capability context for a task.
- Default
Dependency Config - Default dependency configuration (cache per request).
- Dependency
Cache - Request-scoped dependency cache.
- Dependency
Overrides - Dependency override registry (primarily for testing).
- Depends
- Dependency injection extractor.
- Depends
Cleanup - Wrapper for dependencies that have cleanup callbacks.
- File
Response - File response for serving files.
- Form
- URL-encoded form data extractor.
- Form
Extract Error - Error when form extraction fails.
- Hash
Config - Configuration for password hashing.
- Header
- Header extractor for individual HTTP headers.
- Header
Values - Multiple header values extractor.
- Headers
- HTTP headers collection.
- Host
- Host header marker.
- Html
- HTML response with proper content-type.
- Json
- JSON body extractor.
- Json
Config - Configuration for JSON extraction.
- Link
- A single link entry in a Link header.
- Link
Header - Builder for constructing RFC 8288 Link headers.
- Named
Header - Named header extractor with explicit header name.
- NoCache
- Disable caching for this dependency.
- NoContent
- No Content (204) response.
- OAuth2
Bearer Error - Error when OAuth2 bearer token extraction fails.
- OAuth2
Password Bearer - OAuth2 password bearer security scheme extractor.
- OAuth2
Password Bearer Config - Configuration for OAuth2PasswordBearer extraction.
- Page
- Generic paginated response payload.
- Pagination
- Pagination extractor: reads
?page=and?per_page=from the query string. - Pagination
Config - Pagination extractor configuration.
- Password
Hasher - Password hasher with configurable algorithm and work factors.
- Path
- Path parameter extractor.
- Path
Params - Extracted path parameters stored in request extensions.
- Query
- Query string extractor.
- Query
Params - Stored query parameters for extraction.
- Redirect
- HTTP redirect response.
- Region
Id - A unique identifier for a region in the runtime.
- Request
- HTTP request.
- Request
Context - Request context that wraps asupersync’s capability context.
- Response
- HTTP response.
- Response
Model Config - Configuration for response model serialization.
- Session
Id - Session ID cookie marker.
- SetCookie
- Response cookie builder (serialized into a
Set-Cookieheader). - State
- State extractor for application-wide shared state.
- Status
Code - HTTP status code.
- TaskId
- A unique identifier for a task in the runtime.
- Text
- Plain text response with proper content-type.
- User
Agent - User-Agent header marker.
- Valid
- Validated extractor wrapper.
- Validated
Response - A validated response with its configuration.
- XRequest
Id - X-Request-Id header marker.
Enums§
- Algorithm
- Supported hashing algorithms.
- ApiKey
Error Kind - The specific kind of API key error.
- ApiKey
Location - API key extraction location.
- Basic
Auth Error Kind - The specific kind of Basic Auth error.
- Bearer
Token Error Kind - The specific kind of bearer token error.
- Body
- Request body.
- Cookie
Extract Error Kind - The specific kind of cookie extraction error.
- Dependency
Scope - Dependency resolution scope.
- Form
Extract Error Kind - The specific kind of form extraction error.
- Header
Extract Error - Error returned when header extraction fails.
- Http
Version - HTTP protocol version.
- Json
Extract Error - Error returned when JSON extraction fails.
- LinkRel
- Link relation type per RFC 8288.
- Method
- HTTP method.
- Multipart
Extract Error - Error when multipart extraction fails.
- OAuth2
Bearer Error Kind - The specific kind of OAuth2 bearer error.
- Outcome
- The four-valued outcome of a concurrent operation.
- Path
Extract Error - Error returned when path extraction fails.
- Query
Extract Error - Error type for query string extraction failures.
- Request
Body Stream Error - Error yielded by streaming request bodies.
- Response
Body - Response body.
- Same
Site - SameSite cookie attribute.
- State
Extract Error - Error returned when state extraction fails.
- Valid
Extract Error - Error returned when validated extraction fails.
Constants§
- DEFAULT_
JSON_ LIMIT - Default maximum JSON body size (1MB).
- DEFAULT_
PAGE - Default page number used when
pageis not provided. - DEFAULT_
PER_ PAGE - Default items-per-page used when
per_pageis not provided. - MAX_
PER_ PAGE - Maximum allowed
per_pagevalue.
Traits§
- Cookie
Name - Trait for cookie name markers (similar to HeaderName).
- Depends
Config - Configuration for
Dependsresolution. - From
Dependency - Trait for types that can be injected as dependencies.
- From
Dependency With Cleanup - Trait for dependencies that require cleanup after handler completion.
- From
Header Value - Trait for types that can be extracted from header values.
- From
Request - Trait for types that can be extracted from a request.
- Header
Name - Trait for header name markers.
- Into
Outcome - Extension trait for converting HTTP results to asupersync Outcome.
- Into
Response - Trait for types that can be converted into a response.
- Response
Model Aliases - Compile-time response model metadata: canonical field names to alias field names.
- Response
Produces - Marker trait for compile-time response type verification.
- Secure
Compare - Trait providing a timing-safe equality check (
secure_eq) for common types.
Functions§
- apply_
conditional - Evaluate conditional request headers against a response and return the appropriate response (304, 412, or the original).
- check_
if_ match - Check an
If-Matchheader value against an ETag. - check_
if_ none_ match - Check an
If-None-Matchheader value against an ETag. - constant_
time_ eq - Timing-safe byte comparison.
- exclude_
fields - Macro helper for creating validated responses with field exclusion.
- include_
fields - Macro helper for creating validated responses with field inclusion.
- mime_
type_ for_ extension - Get MIME type for a file extension.
- snake_
to_ header_ case - Convert a snake_case name to Header-Case.
Type Aliases§
- Background
Tasks Inner - Request-scoped background tasks to execute after the response is sent.
- Body
Stream - Streamed response body type.
- Default
Config - Backwards-friendly alias for the default config.
- Request
Body Stream - Streamed request body type (yields chunks or a streaming error).