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
§Role In The System
fastapi-core is the heart of the framework. It defines the request/response
model, extractors, dependency injection, middleware, and application builder.
Other crates layer on top of these types:
fastapire-exports this crate as the public facade.fastapi-httpuses core types when parsing and serving HTTP.fastapi-routerplugs into core routing and parameter extraction.fastapi-openapibuilds schemas and specs from core metadata.
This crate intentionally contains no network I/O. That separation keeps business logic and protocol parsing decoupled, and makes deterministic tests straightforward.
§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 error::DebugConfig;pub use error::DebugInfo;pub use error::HttpError;pub use error::LocItem;pub use error::ResponseValidationError;pub use error::ValidationError;pub use error::ValidationErrors;pub use error::disable_debug_mode;pub use error::enable_debug_mode;pub use error::is_debug_mode_enabled;pub use middleware::AddResponseHeader;pub use middleware::BoxFuture;pub use middleware::CompositeKeyExtractor;pub use middleware::ConditionalInterceptor;pub use middleware::ControlFlow;pub use middleware::Cors;pub use middleware::CorsConfig;pub use middleware::CsrfConfig;pub use middleware::CsrfMiddleware;pub use middleware::CsrfMode;pub use middleware::CsrfToken;pub use middleware::DebugInfoInterceptor;pub use middleware::ErrorResponseTransformer;pub use middleware::Handler;pub use middleware::HeaderKeyExtractor;pub use middleware::HeaderTransformInterceptor;pub use middleware::HttpsRedirectConfig;pub use middleware::HttpsRedirectMiddleware;pub use middleware::InspectionVerbosity;pub use middleware::IpKeyExtractor;pub use middleware::KeyExtractor;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::PathKeyExtractor;pub use middleware::PathPrefixFilter;pub use middleware::RateLimitAlgorithm;pub use middleware::RateLimitBuilder;pub use middleware::RateLimitConfig;pub use middleware::RateLimitMiddleware;pub use middleware::RateLimitResult;pub use middleware::ReferrerPolicy;pub use middleware::RequestId;pub use middleware::RequestIdConfig;pub use middleware::RequestIdMiddleware;pub use middleware::RequestInspectionMiddleware;pub use middleware::RequestResponseLogger;pub use middleware::RequireHeader;pub use middleware::ResponseBodyTransform;pub use middleware::ResponseInterceptor;pub use middleware::ResponseInterceptorContext;pub use middleware::ResponseInterceptorMiddleware;pub use middleware::ResponseInterceptorStack;pub use middleware::SecurityHeaders;pub use middleware::SecurityHeadersConfig;pub use middleware::ServerTimingBuilder;pub use middleware::ServerTimingEntry;pub use middleware::TimingHistogram;pub use middleware::TimingHistogramBucket;pub use middleware::TimingInterceptor;pub use middleware::TimingMetrics;pub use middleware::TimingMetricsConfig;pub use middleware::TimingMetricsMiddleware;pub use middleware::TraceRejectionMiddleware;pub use middleware::XFrameOptions;pub use ndjson::NDJSON_CONTENT_TYPE;pub use ndjson::NDJSON_CONTENT_TYPE_ALT;pub use ndjson::NdjsonConfig;pub use ndjson::NdjsonResponse;pub use ndjson::NdjsonStream;pub use ndjson::ndjson_iter;pub use ndjson::ndjson_response;pub use sse::SseConfig;pub use sse::SseEvent;pub use sse::SseResponse;pub use sse::SseStream;pub use sse::sse_response;pub use static_files::StaticFiles;pub use static_files::StaticFilesConfig;pub use testing::CapturedLog;pub use testing::CookieJar;pub use testing::E2ECapture;pub use testing::E2EReport;pub use testing::E2EScenario;pub use testing::E2EStep;pub use testing::E2EStepResult;pub use testing::FixtureGuard;pub use testing::IntegrationTest;pub use testing::IntegrationTestContext;pub use testing::LogCapture;pub use testing::RequestBuilder;pub use testing::ResponseDiff;pub use testing::ResponseSnapshot;pub use testing::TestClient;pub use testing::TestFixture;pub use testing::TestLogger;pub use testing::TestResponse;pub use testing::TestServer;pub use testing::TestServerConfig;pub use testing::TestServerLogEntry;pub use testing::TestTimings;pub use testing::json_contains;pub use coverage::BranchHits;pub use coverage::CoverageConfig;pub use coverage::CoverageReport;pub use coverage::CoverageTracker;pub use coverage::EndpointHits;pub use coverage::OutputFormat;pub use fault::FaultConfig;pub use fault::FaultInjector;pub use fault::FaultRule;pub use fault::FaultType;pub use fixtures::AuthFactory;pub use fixtures::CommonFixtures;pub use fixtures::JsonArrayFactory;pub use fixtures::JsonFactory;pub use fixtures::JsonObjectFactory;pub use fixtures::JwtFactory;pub use fixtures::RequestFactory;pub use fixtures::ResponseFactory;pub use fixtures::UserFactory;pub use loadtest::LoadTest;pub use loadtest::LoadTestConfig;pub use loadtest::LoadTestReport;pub use password::Algorithm;pub use password::HashConfig;pub use password::PasswordHasher;pub use logging::AutoSpan;pub use logging::LogConfig;pub use logging::LogEntry;pub use logging::LogLevel;pub use logging::Span;pub use health::HealthCheckRegistry;pub use health::HealthCheckResult;pub use health::HealthReport;pub use health::HealthStatus;pub use health::basic_health_handler;pub use health::detailed_health_handler;pub use health::liveness_handler;pub use health::readiness_handler;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 api_router::APIRouter;pub use api_router::IncludeConfig;pub use api_router::ResponseDef;pub use api_router::RouterDependency;pub use api_router::RouterRoute;pub use app::App;pub use app::AppBuilder;pub use app::AppConfig;pub use app::BoxLifespanFn;pub use app::ConfigError;pub use app::ExceptionHandlers;pub use app::HasState;pub use app::LifespanError;pub use app::LifespanScope;pub use app::MountedApp;pub use app::RequiresState;pub use app::RouteEntry;pub use app::StartupHook;pub use app::StartupHookError;pub use app::StartupOutcome;pub use app::StateContainer;pub use app::StateRegistry;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;pub use versioning::ApiVersion;pub use versioning::VersionConfig;pub use versioning::VersionStrategy;pub use routing::Converter;pub use routing::ParamInfo;pub use routing::PathSegment;pub use routing::RouteLookup;pub use routing::RoutePattern;pub use routing::RouteTable;pub use routing::TrailingSlashMode;pub use routing::format_allow_header;
Modules§
- api_
router - APIRouter for modular route organization.
- app
- Application builder and runtime for fastapi_rust.
- bench
- Latency measurement and benchmarking utilities.
- coverage
- Code coverage integration for fastapi_rust.
- docs
- Interactive API documentation endpoints.
- error
- Error types.
- fault
- Fault injection for resilience testing.
- fixtures
- Test fixtures and factory helpers for reducing test boilerplate.
- health
- Health check endpoint helpers for operations.
- loadtest
- Load testing utilities for stress testing request handlers.
- logging
- Structured logging infrastructure for fastapi_rust.
- middleware
- Middleware abstraction for request/response processing.
- ndjson
- Newline-Delimited JSON (NDJSON) streaming support.
- password
- Password hashing utilities for secure credential storage.
- routing
- Path matching and routing utilities.
- shutdown
- Graceful shutdown coordination for the server.
- sse
- Server-Sent Events (SSE) support.
- static_
files - Static file serving for fastapi_rust.
- testing
- Test utilities for fastapi applications.
- versioning
- API versioning patterns.
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.
- Accept
Encoding Header - Parsed Accept-Encoding header.
- Accept
Encoding Item - A single entry from an Accept-Encoding header.
- Accept
Header - Parsed Accept header with quality-ordered media types.
- Accept
Item - A single entry from an Accept header with quality value.
- Accept
Language Header - Parsed Accept-Language header.
- Accept
Language Item - A single entry from an Accept-Language header.
- ApiKey
Cookie - Extracts an API key from a cookie.
- ApiKey
Cookie Config - Configuration for API key cookie extraction.
- ApiKey
Header - API key extracted from a request header.
- ApiKey
Header Config - Configuration for API key header extraction.
- ApiKey
Query - Extracts an API key from a query parameter.
- ApiKey
Query Config - Configuration for API key query parameter extraction.
- AppState
- Application state container.
- Authorization
- Authorization header marker.
- Background
Tasks - Background task queue for running tasks after response is sent.
- Background
Tasks Inner - Internal storage for background tasks (thread-safe).
- Basic
Auth - Extracts HTTP Basic authentication credentials from the
Authorizationheader. - Bearer
Token - Simple HTTP bearer token extractor.
- Binary
- Binary response with
application/octet-streamcontent type. - Binary
With Type - Binary response with a custom content type.
- Body
Limit Config - Configuration for request body limits.
- Budget
- A budget constraining resource usage for a task or region.
- Bytes
- Raw bytes body extractor.
- Cancelled
Error - Error returned when a request has been cancelled.
- Circular
Dependency Error - Error returned when a circular dependency is detected.
- Cleanup
Stack - Stack of cleanup functions to run after handler completion.
- Content
Type - Content-Type header marker.
- Cookie
- A cookie to set in the response.
- Csrf
Token Cookie - CSRF token cookie name marker.
- 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).
- Dependency
Scope Error - Error returned when a dependency scope constraint is violated.
- Depends
- Dependency injection extractor.
- Depends
Cleanup - Wrapper for dependencies that have cleanup callbacks.
- Digest
Auth - HTTP Digest authentication credentials extractor (stub).
- File
- File extractor for a single file upload.
- File
Config - Configuration for the File extractor.
- File
Response - File response for serving files.
- Form
- Form body extractor for
application/x-www-form-urlencoded. - Form
Config - Configuration for form extraction.
- 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 request body extraction.
- Link
- A single link entry in a Link header.
- Link
Header - Builder for constructing RFC 8288 Link headers.
- Media
Type - A parsed media type (MIME type) with optional parameters.
- Multipart
- Multipart form data extractor.
- Multipart
Config - Configuration for multipart form extraction.
- Multipart
Part - A part of a multipart form (either a field or a file).
- Named
Header - Named header extractor with explicit header name.
- NoCache
- Disable caching for this dependency.
- NoContent
- No Content (204) response.
- NotAcceptable
Error - Error returned when content negotiation fails.
- OAuth2
Authorization Code Bearer - OAuth2 authorization code bearer extractor.
- OAuth2
Authorization Code Bearer Config - Configuration for OAuth2 authorization code bearer extraction.
- 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.
- OAuth2
Password Request Form - OAuth2 password request form data.
- OAuth2
Password Request Form Strict - Strict variant of
OAuth2PasswordRequestForm. - Page
- Paginated response wrapper.
- Pagination
- Pagination query parameters extractor.
- Pagination
Config - Configuration for pagination behavior.
- Path
- Path parameter extractor.
- Path
Params - Extracted path parameters stored in request extensions.
- Query
- Query string extractor.
- Query
Params - Stored query parameters for extraction.
- RawBody
Config - Configuration for raw body extraction.
- Redirect
- HTTP redirect response.
- Region
Id - A unique identifier for a region in the runtime.
- Request
- HTTP request.
- Request
Body Stream - A streaming request body.
- Request
Context - Request context that wraps asupersync’s capability context.
- Request
Cookie - Extract a single cookie value by name from the incoming request.
- Request
Cookies - Extract all cookies from the incoming request as a map.
- Request
Ref - Read-only request data access.
- Response
- HTTP response.
- Response
Model Config - Configuration for response model serialization.
- Response
Mut - Mutable response wrapper for setting headers and cookies.
- Response
Mutations - Mutable response container for setting response headers and cookies.
- Security
Scopes - Required OAuth2 security scopes for a handler.
- Security
Scopes Error - Error when SecurityScopes extraction fails.
- Session
IdCookie - Session ID cookie name marker.
- State
- State extractor for application-wide shared state.
- Status
Code - HTTP status code.
- String
Body - String body extractor.
- TaskId
- A unique identifier for a task in the runtime.
- Text
- Plain text response with proper content-type.
- Uploaded
File - An uploaded file extracted from a multipart form.
- User
Agent - User-Agent header marker.
- Validated
Response - A validated response with its configuration.
- Vary
Builder - Helper to build Vary header values for content negotiation.
- XRequest
Id - X-Request-Id header marker.
Enums§
- ApiKey
Cookie Error - Error returned when API key cookie extraction fails.
- ApiKey
Header Error - Error returned when API key header extraction fails.
- ApiKey
Query Error - Error returned when API key query parameter extraction fails.
- Basic
Auth Error - Error when basic auth extraction fails.
- Bearer
Token Error - Error when bearer token extraction fails.
- Body
- Request body.
- Cookie
Extract Error - Error type for cookie extraction failures.
- Cookie
Prefix - Cookie security prefix types.
- Cookie
Prefix Error - Errors that can occur when validating cookie prefixes.
- Dependency
Scope - Dependency resolution scope.
- Digest
Auth Error - Error when Digest auth extraction fails.
- Form
Extract Error - Error for form extraction failures.
- Header
Extract Error - Error returned when header extraction fails.
- Http
Version - HTTP version.
- Json
Extract Error - Error returned when JSON extraction fails.
- LinkRel
- Link relation type per RFC 8288.
- Method
- HTTP method.
- Multipart
Extract Error - Error for multipart form extraction failures.
- OAuth2
Bearer Error Kind - The specific kind of OAuth2 bearer error.
- OAuth2
Password Form Error - Error when OAuth2 password request form extraction fails.
- 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.
- RawBody
Error - Error for raw body extraction failures.
- Request
Body Stream Error - Error type for streaming body operations.
- Response
Body - Response body.
- Same
Site - SameSite cookie attribute.
- State
Extract Error - Error returned when state extraction fails.
Constants§
- DEFAULT_
API_ KEY_ COOKIE - Default cookie name for API key extraction.
- DEFAULT_
API_ KEY_ HEADER - Default header name for API key extraction.
- DEFAULT_
API_ KEY_ QUERY_ PARAM - Default query parameter name for API key extraction.
- DEFAULT_
FORM_ LIMIT - Default maximum form body size (1MB).
- DEFAULT_
JSON_ LIMIT - Default maximum JSON body size (1MB).
- DEFAULT_
MAX_ BODY_ SIZE - Default maximum body size: 1MB.
- DEFAULT_
MULTIPART_ FILE_ SIZE - Default maximum file size for multipart uploads (10MB).
- DEFAULT_
MULTIPART_ MAX_ FIELDS - Default maximum number of fields in multipart form.
- DEFAULT_
MULTIPART_ TOTAL_ SIZE - Default maximum total size for multipart uploads (50MB).
- DEFAULT_
PAGE - Default page number (1-indexed).
- DEFAULT_
PER_ PAGE - Default items per page.
- DEFAULT_
RAW_ BODY_ LIMIT - Default maximum raw body size (2MB).
- MAX_
PER_ PAGE - Maximum items per page (to prevent abuse).
Traits§
- Cookie
Name - Trait for defining cookie names used with
RequestCookie<T>. - 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 - Trait for types that can be validated as response models.
- Response
Produces - Marker trait for compile-time response type verification.
- Secure
Compare - Extension trait for constant-time equality comparison on
BearerToken.
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 - Performs constant-time comparison of two byte slices.
- constant_
time_ str_ eq - Performs constant-time comparison of two strings.
- 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§
- Body
Stream - Streamed response body type.
- Cleanup
Fn - Type alias for cleanup functions.
- Default
Config - Backwards-friendly alias for the default config.