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

§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.
ApiKeyConfig
Configuration for API key extraction.
ApiKeyError
Error when API key extraction fails.
AppState
Application state container.
Authorization
Authorization header marker.
BackgroundTasks
BasicAuth
HTTP Basic Authentication credentials extractor.
BasicAuthError
Error when HTTP Basic Auth extraction fails.
BearerToken
Bearer token extractor for Authorization: Bearer <token>.
BearerTokenError
Error when bearer token extraction fails.
Binary
Binary response with application/octet-stream content type.
Budget
A budget constraining resource usage for a task or region.
CancelledError
Error returned when a request has been cancelled.
ContentType
Content-Type header marker.
Cookie
Cookie value extractor.
CookieExtractError
Error when cookie extraction fails.
CsrfToken
CSRF token cookie marker.
CsrfTokenCookie
CSRF token cookie marker (compat alias used by some middleware/tests).
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).
Depends
Dependency injection extractor.
DependsCleanup
Wrapper for dependencies that have cleanup callbacks.
FileResponse
File response for serving files.
Form
URL-encoded form data extractor.
FormExtractError
Error when form extraction fails.
HashConfig
Configuration for password hashing.
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 extraction.
Link
A single link entry in a Link header.
LinkHeader
Builder for constructing RFC 8288 Link headers.
NamedHeader
Named header extractor with explicit header name.
NoCache
Disable caching for this dependency.
NoContent
No Content (204) response.
OAuth2BearerError
Error when OAuth2 bearer token extraction fails.
OAuth2PasswordBearer
OAuth2 password bearer security scheme extractor.
OAuth2PasswordBearerConfig
Configuration for OAuth2PasswordBearer extraction.
Page
Generic paginated response payload.
Pagination
Pagination extractor: reads ?page= and ?per_page= from the query string.
PaginationConfig
Pagination extractor configuration.
PasswordHasher
Password hasher with configurable algorithm and work factors.
Path
Path parameter extractor.
PathParams
Extracted path parameters stored in request extensions.
Query
Query string extractor.
QueryParams
Stored query parameters for extraction.
Redirect
HTTP redirect response.
RegionId
A unique identifier for a region in the runtime.
Request
HTTP request.
RequestContext
Request context that wraps asupersync’s capability context.
Response
HTTP response.
ResponseModelConfig
Configuration for response model serialization.
SessionId
Session ID cookie marker.
SetCookie
Response cookie builder (serialized into a Set-Cookie header).
State
State extractor for application-wide shared state.
StatusCode
HTTP status code.
TaskId
A unique identifier for a task in the runtime.
Text
Plain text response with proper content-type.
UserAgent
User-Agent header marker.
Valid
Validated extractor wrapper.
ValidatedResponse
A validated response with its configuration.
XRequestId
X-Request-Id header marker.

Enums§

Algorithm
Supported hashing algorithms.
ApiKeyErrorKind
The specific kind of API key error.
ApiKeyLocation
API key extraction location.
BasicAuthErrorKind
The specific kind of Basic Auth error.
BearerTokenErrorKind
The specific kind of bearer token error.
Body
Request body.
CookieExtractErrorKind
The specific kind of cookie extraction error.
DependencyScope
Dependency resolution scope.
FormExtractErrorKind
The specific kind of form extraction error.
HeaderExtractError
Error returned when header extraction fails.
HttpVersion
HTTP protocol version.
JsonExtractError
Error returned when JSON extraction fails.
LinkRel
Link relation type per RFC 8288.
Method
HTTP method.
MultipartExtractError
Error when multipart extraction fails.
OAuth2BearerErrorKind
The specific kind of OAuth2 bearer error.
Outcome
The four-valued outcome of a concurrent operation.
PathExtractError
Error returned when path extraction fails.
QueryExtractError
Error type for query string extraction failures.
RequestBodyStreamError
Error yielded by streaming request bodies.
ResponseBody
Response body.
SameSite
SameSite cookie attribute.
StateExtractError
Error returned when state extraction fails.
ValidExtractError
Error returned when validated extraction fails.

Constants§

DEFAULT_JSON_LIMIT
Default maximum JSON body size (1MB).
DEFAULT_PAGE
Default page number used when page is not provided.
DEFAULT_PER_PAGE
Default items-per-page used when per_page is not provided.
MAX_PER_PAGE
Maximum allowed per_page value.

Traits§

CookieName
Trait for cookie name markers (similar to HeaderName).
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.
ResponseModelAliases
Compile-time response model metadata: canonical field names to alias field names.
ResponseProduces
Marker trait for compile-time response type verification.
SecureCompare
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-Match header value against an ETag.
check_if_none_match
Check an If-None-Match header 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§

BackgroundTasksInner
Request-scoped background tasks to execute after the response is sent.
BodyStream
Streamed response body type.
DefaultConfig
Backwards-friendly alias for the default config.
RequestBodyStream
Streamed request body type (yields chunks or a streaming error).