Skip to main content

Crate fastapi_core

Crate fastapi_core 

Source
Expand description

Core types and traits for fastapi_rust.

This crate provides the fundamental building blocks:

§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:

  • fastapi re-exports this crate as the public facade.
  • fastapi-http uses core types when parsing and serving HTTP.
  • fastapi-router plugs into core routing and parameter extraction.
  • fastapi-openapi builds 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.
AcceptEncodingHeader
Parsed Accept-Encoding header.
AcceptEncodingItem
A single entry from an Accept-Encoding header.
AcceptHeader
Parsed Accept header with quality-ordered media types.
AcceptItem
A single entry from an Accept header with quality value.
AcceptLanguageHeader
Parsed Accept-Language header.
AcceptLanguageItem
A single entry from an Accept-Language header.
ApiKeyCookie
Extracts an API key from a cookie.
ApiKeyCookieConfig
Configuration for API key cookie extraction.
ApiKeyHeader
API key extracted from a request header.
ApiKeyHeaderConfig
Configuration for API key header extraction.
ApiKeyQuery
Extracts an API key from a query parameter.
ApiKeyQueryConfig
Configuration for API key query parameter extraction.
AppState
Application state container.
Authorization
Authorization header marker.
BackgroundTasks
Background task queue for running tasks after response is sent.
BackgroundTasksInner
Internal storage for background tasks (thread-safe).
BasicAuth
Extracts HTTP Basic authentication credentials from the Authorization header.
BearerToken
Simple HTTP bearer token extractor.
Binary
Binary response with application/octet-stream content type.
BinaryWithType
Binary response with a custom content type.
BodyLimitConfig
Configuration for request body limits.
Budget
A budget constraining resource usage for a task or region.
Bytes
Raw bytes body extractor.
CancelledError
Error returned when a request has been cancelled.
CircularDependencyError
Error returned when a circular dependency is detected.
CleanupStack
Stack of cleanup functions to run after handler completion.
ContentType
Content-Type header marker.
Cookie
A cookie to set in the response.
CsrfTokenCookie
CSRF token cookie name marker.
Cx
The capability context for a task.
DefaultDependencyConfig
Default dependency configuration (cache per request).
DependencyCache
Request-scoped dependency cache.
DependencyOverrides
Dependency override registry (primarily for testing).
DependencyScopeError
Error returned when a dependency scope constraint is violated.
Depends
Dependency injection extractor.
DependsCleanup
Wrapper for dependencies that have cleanup callbacks.
DigestAuth
HTTP Digest authentication credentials extractor (stub).
File
File extractor for a single file upload.
FileConfig
Configuration for the File extractor.
FileResponse
File response for serving files.
Form
Form body extractor for application/x-www-form-urlencoded.
FormConfig
Configuration for form extraction.
Header
Header extractor for individual HTTP headers.
HeaderValues
Multiple header values extractor.
Headers
HTTP headers collection.
Host
Host header marker.
Html
HTML response with proper content-type.
Json
JSON body extractor.
JsonConfig
Configuration for JSON request body extraction.
Link
A single link entry in a Link header.
LinkHeader
Builder for constructing RFC 8288 Link headers.
MediaType
A parsed media type (MIME type) with optional parameters.
Multipart
Multipart form data extractor.
MultipartConfig
Configuration for multipart form extraction.
MultipartPart
A part of a multipart form (either a field or a file).
NamedHeader
Named header extractor with explicit header name.
NoCache
Disable caching for this dependency.
NoContent
No Content (204) response.
NotAcceptableError
Error returned when content negotiation fails.
OAuth2AuthorizationCodeBearer
OAuth2 authorization code bearer extractor.
OAuth2AuthorizationCodeBearerConfig
Configuration for OAuth2 authorization code bearer extraction.
OAuth2BearerError
Error when OAuth2 bearer token extraction fails.
OAuth2PasswordBearer
OAuth2 password bearer security scheme extractor.
OAuth2PasswordBearerConfig
Configuration for OAuth2PasswordBearer extraction.
OAuth2PasswordRequestForm
OAuth2 password request form data.
OAuth2PasswordRequestFormStrict
Strict variant of OAuth2PasswordRequestForm.
Page
Paginated response wrapper.
Pagination
Pagination query parameters extractor.
PaginationConfig
Configuration for pagination behavior.
Path
Path parameter extractor.
PathParams
Extracted path parameters stored in request extensions.
Query
Query string extractor.
QueryParams
Stored query parameters for extraction.
RawBodyConfig
Configuration for raw body extraction.
Redirect
HTTP redirect response.
RegionId
A unique identifier for a region in the runtime.
Request
HTTP request.
RequestBodyStream
A streaming request body.
RequestContext
Request context that wraps asupersync’s capability context.
RequestCookie
Extract a single cookie value by name from the incoming request.
RequestCookies
Extract all cookies from the incoming request as a map.
RequestRef
Read-only request data access.
Response
HTTP response.
ResponseModelConfig
Configuration for response model serialization.
ResponseMut
Mutable response wrapper for setting headers and cookies.
ResponseMutations
Mutable response container for setting response headers and cookies.
SecurityScopes
Required OAuth2 security scopes for a handler.
SecurityScopesError
Error when SecurityScopes extraction fails.
SessionIdCookie
Session ID cookie name marker.
State
State extractor for application-wide shared state.
StatusCode
HTTP status code.
StringBody
String body extractor.
TaskId
A unique identifier for a task in the runtime.
Text
Plain text response with proper content-type.
UploadedFile
An uploaded file extracted from a multipart form.
UserAgent
User-Agent header marker.
ValidatedResponse
A validated response with its configuration.
VaryBuilder
Helper to build Vary header values for content negotiation.
XRequestId
X-Request-Id header marker.

Enums§

ApiKeyCookieError
Error returned when API key cookie extraction fails.
ApiKeyHeaderError
Error returned when API key header extraction fails.
ApiKeyQueryError
Error returned when API key query parameter extraction fails.
BasicAuthError
Error when basic auth extraction fails.
BearerTokenError
Error when bearer token extraction fails.
Body
Request body.
CookieExtractError
Error type for cookie extraction failures.
CookiePrefix
Cookie security prefix types.
CookiePrefixError
Errors that can occur when validating cookie prefixes.
DependencyScope
Dependency resolution scope.
DigestAuthError
Error when Digest auth extraction fails.
FormExtractError
Error for form extraction failures.
HeaderExtractError
Error returned when header extraction fails.
HttpVersion
HTTP version.
JsonExtractError
Error returned when JSON extraction fails.
LinkRel
Link relation type per RFC 8288.
Method
HTTP method.
MultipartExtractError
Error for multipart form extraction failures.
OAuth2BearerErrorKind
The specific kind of OAuth2 bearer error.
OAuth2PasswordFormError
Error when OAuth2 password request form extraction fails.
Outcome
The four-valued outcome of a concurrent operation.
PathExtractError
Error returned when path extraction fails.
QueryExtractError
Error type for query string extraction failures.
RawBodyError
Error for raw body extraction failures.
RequestBodyStreamError
Error type for streaming body operations.
ResponseBody
Response body.
SameSite
SameSite cookie attribute.
StateExtractError
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§

CookieName
Trait for defining cookie names used with RequestCookie<T>.
DependsConfig
Configuration for Depends resolution.
FromDependency
Trait for types that can be injected as dependencies.
FromDependencyWithCleanup
Trait for dependencies that require cleanup after handler completion.
FromHeaderValue
Trait for types that can be extracted from header values.
FromRequest
Trait for types that can be extracted from a request.
HeaderName
Trait for header name markers.
IntoOutcome
Extension trait for converting HTTP results to asupersync Outcome.
IntoResponse
Trait for types that can be converted into a response.
ResponseModel
Trait for types that can be validated as response models.
ResponseProduces
Marker trait for compile-time response type verification.
SecureCompare
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-Match header value against an ETag.
check_if_none_match
Check an If-None-Match header 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§

BodyStream
Streamed response body type.
CleanupFn
Type alias for cleanup functions.
DefaultConfig
Backwards-friendly alias for the default config.