Skip to content

Python API Reference

Python API Reference v0.17.0-rc.4

Functions

schema_query_only()

Create a simple schema configuration with only Query type.

This is a convenience function for schemas that only have queries.

Returns:

A QueryOnlyConfig with default settings

Signature:

def schema_query_only() -> QueryOnlyConfig

Example:

result = schema_query_only()

Returns: QueryOnlyConfig


schema_query_mutation()

Create a schema configuration with Query and Mutation types.

This is a convenience function for schemas with queries and mutations but no subscriptions.

Returns:

A QueryMutationConfig with default settings

Signature:

def schema_query_mutation() -> QueryMutationConfig

Example:

result = schema_query_mutation()

Returns: QueryMutationConfig


schema_full()

Create a schema configuration with all three root types.

This is a convenience function for fully-featured schemas.

Returns:

A FullSchemaConfig with default settings

Signature:

def schema_full() -> FullSchemaConfig

Example:

result = schema_full()

Returns: FullSchemaConfig


Types

ApiKeyConfig

API Key authentication configuration

Field Type Default Description
keys list\[str\] Valid API keys
header_name str serde(default = "default_api_key_header") Header name to check (e.g., "X-API-Key")

AsyncApiConfig

AsyncAPI HTTP endpoint configuration

Field Type Default Description
enabled bool Enable AsyncAPI endpoints (default: false)
spec dict\[str, Any\] \| None None Pre-registered AsyncAPI spec to serve from GET /asyncapi.json

BackgroundJobMetadata

Field Type Default Description
name str The name
request_id str \| None None Request id
Methods
default()

Signature:

@staticmethod
def default() -> BackgroundJobMetadata

Example:

result = BackgroundJobMetadata.default()

Returns: BackgroundJobMetadata


BackgroundTaskConfig

Configuration for in-process background task execution.

Field Type Default Description
max_queue_size int 1024 Maximum queue size
max_concurrent_tasks int 128 Maximum concurrent tasks
drain_timeout_secs int 30 Drain timeout secs
Methods
default()

Signature:

@staticmethod
def default() -> BackgroundTaskConfig

Example:

result = BackgroundTaskConfig.default()

Returns: BackgroundTaskConfig


CompressionConfig

Compression configuration shared across runtimes

Field Type Default Description
gzip bool True Enable gzip compression
brotli bool True Enable brotli compression
min_size int Minimum response size to compress (bytes)
quality int Compression quality (0-11 for brotli, 0-9 for gzip)
Methods
default()

Signature:

@staticmethod
def default() -> CompressionConfig

Example:

result = CompressionConfig.default()

Returns: CompressionConfig


ContactInfo

Contact information

Field Type Default Description
name str \| None None Name of the contact person or organisation.
email str \| None None Contact email address.
url str \| None None URL pointing to the contact information page.

CorsConfig

CORS configuration for a route

Field Type Default Description
allowed_origins list\[str\] \[\] Allowed origins
allowed_methods list\[str\] \[\] Allowed methods
allowed_headers list\[str\] \[\] Allowed headers
expose_headers list\[str\] \| None None Expose headers
max_age int \| None None Maximum age
allow_credentials bool \| None None Allow credentials
Methods
allowed_methods_joined()

Get the cached joined methods string for preflight responses

Signature:

def allowed_methods_joined(self) -> str

Example:

result = instance.allowed_methods_joined()

Returns: str

allowed_headers_joined()

Get the cached joined headers string for preflight responses

Signature:

def allowed_headers_joined(self) -> str

Example:

result = instance.allowed_headers_joined()

Returns: str

is_origin_allowed()

Check if an origin is allowed (O(1) with wildcard, O(n) for exact match)

Signature:

def is_origin_allowed(self, origin: str) -> bool

Example:

result = instance.is_origin_allowed("value")

Parameters:

Name Type Required Description
origin str Yes The origin

Returns: bool

is_method_allowed()

Check if a method is allowed (O(1) with wildcard, O(n) for exact match)

Signature:

def is_method_allowed(self, method: str) -> bool

Example:

result = instance.is_method_allowed("value")

Parameters:

Name Type Required Description
method str Yes The method

Returns: bool

default()

Signature:

@staticmethod
def default() -> CorsConfig

Example:

result = CorsConfig.default()

Returns: CorsConfig


DynamicSchemaConfig

Configuration for building and executing a dynamic-SDL schema.

Field Type Default Description
introspection_enabled bool Whether introspection queries (__schema, __type) are permitted.
max_complexity int \| None None Maximum query complexity (None = unlimited).
max_depth int \| None None Maximum query depth (None = unlimited).
field_errors list\[FieldErrorSpec\] \[\] Field-level errors to inject at specific response paths.

FieldErrorSpec

A field-level error to inject at a specific response path.

path is the dot-separated sequence of field names from the operation root to the field that should fail, e.g. "user" for a top-level field or "order.customer" for a nested one.

Field Type Default Description
path str Dot-separated path to the field that should error.
message str The error message to surface for that field.

FullSchemaConfig

Configuration for fully-featured schemas with Query, Mutation, and Subscription types

Field Type Default Description
introspection_enabled bool True Enable introspection queries
complexity_limit int \| None None Maximum query complexity (None = unlimited)
depth_limit int \| None None Maximum query depth (None = unlimited)
Methods
default()

Signature:

@staticmethod
def default() -> FullSchemaConfig

Example:

result = FullSchemaConfig.default()

Returns: FullSchemaConfig


GraphQlRouteConfig

Configuration for GraphQL routes

Provides a builder pattern for configuring GraphQL route parameters for the Spikard HTTP server's routing system.

Methods
new()

Create a new GraphQL route configuration with defaults

Default values:

  • path: "/graphql"
  • method: "POST"
  • enable_playground: false

Signature:

@staticmethod
def new() -> GraphQlRouteConfig

Example:

result = GraphQlRouteConfig.new()

Returns: GraphQlRouteConfig

path()

Set the HTTP path for the GraphQL endpoint

Signature:

def path(self, path: str) -> GraphQlRouteConfig

Example:

result = instance.path("value")

Parameters:

Name Type Required Description
path str Yes The URL path (e.g., "/graphql", "/api/graphql")

Returns: GraphQlRouteConfig

method()

Set the HTTP method for the GraphQL endpoint

Signature:

def method(self, method: str) -> GraphQlRouteConfig

Example:

result = instance.method("value")

Parameters:

Name Type Required Description
method str Yes The HTTP method (typically "POST")

Returns: GraphQlRouteConfig

enable_playground()

Enable or disable the GraphQL Playground UI

Signature:

def enable_playground(self, enable: bool) -> GraphQlRouteConfig

Example:

result = instance.enable_playground(True)

Parameters:

Name Type Required Description
enable bool Yes Whether to enable playground

Returns: GraphQlRouteConfig

description()

Set a custom description for documentation

Signature:

def description(self, description: str) -> GraphQlRouteConfig

Example:

result = instance.description("value")

Parameters:

Name Type Required Description
description str Yes Documentation string

Returns: GraphQlRouteConfig

get_path()

Get the configured path

Signature:

def get_path(self) -> str

Example:

result = instance.get_path()

Returns: str

get_method()

Get the configured method

Signature:

def get_method(self) -> str

Example:

result = instance.get_method()

Returns: str

is_playground_enabled()

Check if playground is enabled

Signature:

def is_playground_enabled(self) -> bool

Example:

result = instance.is_playground_enabled()

Returns: bool

get_description()

Get the description if set

Signature:

def get_description(self) -> str | None

Example:

result = instance.get_description()

Returns: str | None

default()

Signature:

@staticmethod
def default() -> GraphQlRouteConfig

Example:

result = GraphQlRouteConfig.default()

Returns: GraphQlRouteConfig


GraphQlSubscriptionSnapshot

Snapshot of a GraphQL subscription exchange over WebSocket.

Field Type Default Description
operation_id str Operation id used for the subscription request.
acknowledged bool Whether the server acknowledged the GraphQL WebSocket connection.
event dict\[str, Any\] \| None None First next.payload received for this subscription, if any.
errors list\[dict\[str, Any\]\] GraphQL protocol errors emitted by the server.
complete_received bool Whether a complete frame was observed for this operation.

GrpcConfig

Configuration for gRPC support

Controls how the server handles gRPC requests, including compression, timeouts, and protocol settings.

Stream Limits

This configuration enforces message-level size limits but delegates concurrent stream limiting to the HTTP/2 transport layer:

  • Message Size Limits: The max_message_size field is enforced per individual message (request or response) in both unary and streaming RPCs. When a single message exceeds this limit, the request is rejected with PAYLOAD_TOO_LARGE (HTTP 413).

  • Concurrent Stream Limits: The max_concurrent_streams is an advisory configuration passed to the HTTP/2 layer for connection-level stream negotiation. The HTTP/2 transport automatically enforces this limit and returns GOAWAY frames when exceeded. Applications should not rely on custom enforcement of this limit.

  • Stream Response Size Limits: The max_stream_response_bytes field caps the total encoded bytes emitted across a server-streaming or bidi-streaming response. When the cumulative size exceeds the limit, the stream is terminated with tonic.Status.resource_exhausted. Defaults to None (unbounded).

Field Type Default Description
enabled bool True Enable gRPC support
max_message_size int Maximum message size in bytes (for both sending and receiving) This limit applies to individual messages in both unary and streaming RPCs. When a single message exceeds this size, the request is rejected with HTTP 413 (Payload Too Large). Default: 4MB (4194304 bytes) Note: This limit does NOT apply to the total response size in streaming RPCs. For multi-message streams, the total response can exceed this limit as long as each individual message stays within the limit.
enable_compression bool True Enable gzip compression for gRPC messages
request_timeout int \| None None Timeout for gRPC requests in seconds (None = no timeout)
max_concurrent_streams int Maximum number of concurrent streams per connection (HTTP/2 advisory) This value is communicated to HTTP/2 clients as the server's flow control limit. The HTTP/2 transport layer enforces this limit automatically via SETTINGS frames and GOAWAY responses. Applications should NOT implement custom enforcement. Default: 100 streams per connection # Stream Limiting Strategy - Per Connection: This limit applies per HTTP/2 connection, not globally - Transport Enforcement: HTTP/2 handles all stream limiting; applications need not implement custom checks - Streaming Requests: In server streaming or bidi streaming, each logical RPC consumes one stream slot. Message ordering within a stream follows HTTP/2 frame ordering.
enable_keepalive bool True Enable HTTP/2 keepalive
keepalive_interval int HTTP/2 keepalive interval in seconds
keepalive_timeout int HTTP/2 keepalive timeout in seconds
max_stream_response_bytes int \| None None Total byte cap across an entire streaming response. When Some(n), the streaming adapter aborts the stream with tonic.Status.resource_exhausted once the cumulative encoded message bytes exceed n. The stream yields the error item and then terminates. Per-message cap remains max_message_size. This limit applies to server-streaming and bidirectional-streaming RPCs only; unary RPCs are governed solely by max_message_size. Default: None (unbounded total response size).
Methods
default()

Signature:

@staticmethod
def default() -> GrpcConfig

Example:

result = GrpcConfig.default()

Returns: GrpcConfig


IntoHandler

Convert user-facing handler functions into the low-level Handler trait.

Methods
into_handler()

Convert this value into a shared request handler.

Signature:

def into_handler(self) -> Handler

Example:

result = instance.into_handler()

Returns: Handler


JsonRpcConfig

JSON-RPC server configuration

Field Type Default Description
enabled bool True Enable JSON-RPC endpoint
endpoint_path str HTTP endpoint path for JSON-RPC requests (default: "/rpc")
enable_batch bool Enable batch request processing (default: true)
max_batch_size int Maximum number of requests in a batch (default: 100)
Methods
default()

Signature:

@staticmethod
def default() -> JsonRpcConfig

Example:

result = JsonRpcConfig.default()

Returns: JsonRpcConfig


JsonRpcMethodInfo

JSON-RPC method metadata for routes that support JSON-RPC

This struct captures the metadata needed to expose HTTP routes as JSON-RPC methods, enabling discovery and documentation of RPC-compatible endpoints.

Field Type Default Description
method_name str The JSON-RPC method name (e.g., "user.create")
description str \| None None Optional description of what the method does
params_schema dict\[str, Any\] \| None None Optional JSON Schema for method parameters
result_schema dict\[str, Any\] \| None None Optional JSON Schema for the result
deprecated bool /* serde(default) */ Whether this method is deprecated
tags list\[str\] /* serde(default) */ Tags for categorizing and grouping methods

JwtConfig

JWT authentication configuration

Field Type Default Description
secret str Secret key for JWT verification
algorithm str serde(default = "default_jwt_algorithm") Required algorithm (HS256, HS384, HS512, RS256, etc.)
audience list\[str\] \| None None Required audience claim
issuer str \| None None Required issuer claim
leeway int /* serde(default) */ Leeway for expiration checks (seconds)

LicenseInfo

License information

Field Type Default Description
name str SPDX license identifier or display name (e.g. "MIT").
url str \| None None URL to the full license text.

OpenApiConfig

OpenAPI configuration

Field Type Default Description
enabled bool False Enable OpenAPI generation (default: false for zero overhead)
title str "API" API title
version str "1.0.0" API version
description str \| None None API description (supports markdown)
swagger_ui_path str Path to serve Swagger UI (default: "/docs")
redoc_path str Path to serve Redoc (default: "/redoc")
openapi_json_path str Path to serve OpenAPI JSON spec (default: "/openapi.json")
contact ContactInfo \| None None Contact information
license LicenseInfo \| None None License information
servers list\[ServerInfo\] \[\] Server definitions
security_schemes dict\[str, SecuritySchemeInfo\] {} Security schemes (auto-detected from middleware if not provided)
Methods
default()

Signature:

@staticmethod
def default() -> OpenApiConfig

Example:

result = OpenApiConfig.default()

Returns: OpenApiConfig


ParseRequest

Request body for POST /asyncapi/parse

Field Type Default Description
spec dict\[str, Any\] Spec

ParseResult

Full parse result returned by POST /asyncapi/parse

Field Type Default Description
spec_version str Spec version
title str Title
api_version str Api version
channels list\[ParsedChannel\] Channels
operations list\[ParsedOperation\] Operations
messages list\[ParsedMessage\] Messages

ParsedChannel

A single channel extracted from an AsyncAPI spec

Field Type Default Description
name str Channel key from the spec (e.g. "chat/messages")
address str Channel address / path
messages list\[str\] Message names declared on this channel
bindings dict\[str, Any\] \| None None Bindings (ws / http / amqp / …) as raw JSON for forward-compatibility

ParsedMessage

A resolved message (name + JSON Schema)

Field Type Default Description
name str Message name
schema dict\[str, Any\] \| None None Resolved JSON Schema for the message payload, if available

ParsedOperation

A single operation extracted from an AsyncAPI spec

Field Type Default Description
name str Operation name
action str Operation action: "send" or "receive"
channel str Channel reference (resolved to the channel name)

ProblemDetails

RFC 9457 Problem Details for HTTP APIs

A machine-readable format for specifying errors in HTTP API responses. Per RFC 9457, all fields are optional. The type field defaults to "about:blank" if not specified.

Content-Type

Responses using this struct should set:

Content-Type: application/problem+json
{
  "type": "<https://spikard.dev/errors/validation-error",>
  "title": "Request Validation Failed",
  "status": 422,
  "detail": "2 validation errors in request body",
  "errors": [...]
}
Field Type Default Description
type_uri str A URI reference that identifies the problem type. Defaults to "about:blank" when absent. Should be a stable, human-readable identifier for the problem type.
title str A short, human-readable summary of the problem type. Should not change from occurrence to occurrence of the problem.
status int The HTTP status code generated by the origin server. This is advisory; the actual HTTP status code takes precedence.
detail str \| None None A human-readable explanation specific to this occurrence of the problem.
instance str \| None None A URI reference that identifies the specific occurrence of the problem. It may or may not yield further information if dereferenced.
extensions dict\[str, dict\[str, Any\]\] Extension members - problem-type-specific data. For validation errors, this typically contains an "errors" array.
Methods
with_detail()

Set the detail field

Signature:

def with_detail(self, detail: str) -> ProblemDetails

Example:

result = instance.with_detail("value")

Parameters:

Name Type Required Description
detail str Yes The detail

Returns: ProblemDetails

with_instance()

Set the instance field

Signature:

def with_instance(self, instance: str) -> ProblemDetails

Example:

result = instance.with_instance("value")

Parameters:

Name Type Required Description
instance str Yes The instance

Returns: ProblemDetails

not_found()

Create a not found error

Signature:

@staticmethod
def not_found(detail: str) -> ProblemDetails

Example:

result = ProblemDetails.not_found("value")

Parameters:

Name Type Required Description
detail str Yes The detail

Returns: ProblemDetails

method_not_allowed()

Create a method not allowed error

Signature:

@staticmethod
def method_not_allowed(detail: str) -> ProblemDetails

Example:

result = ProblemDetails.method_not_allowed("value")

Parameters:

Name Type Required Description
detail str Yes The detail

Returns: ProblemDetails

internal_server_error()

Create an internal server error

Signature:

@staticmethod
def internal_server_error(detail: str) -> ProblemDetails

Example:

result = ProblemDetails.internal_server_error("value")

Parameters:

Name Type Required Description
detail str Yes The detail

Returns: ProblemDetails

bad_request()

Create a bad request error

Signature:

@staticmethod
def bad_request(detail: str) -> ProblemDetails

Example:

result = ProblemDetails.bad_request("value")

Parameters:

Name Type Required Description
detail str Yes The detail

Returns: ProblemDetails

to_json()

Serialize to JSON string

Errors: Returns an error if the serialization fails.

Signature:

def to_json(self) -> str

Example:

result = instance.to_json()

Returns: str

Errors: Raises Error.

to_json_pretty()

Serialize to pretty JSON string

Errors: Returns an error if the serialization fails.

Signature:

def to_json_pretty(self) -> str

Example:

result = instance.to_json_pretty()

Returns: str

Errors: Raises Error.


QueryMutationConfig

Configuration for schemas with Query and Mutation types

Field Type Default Description
introspection_enabled bool True Enable introspection queries
complexity_limit int \| None None Maximum query complexity (None = unlimited)
depth_limit int \| None None Maximum query depth (None = unlimited)
Methods
default()

Signature:

@staticmethod
def default() -> QueryMutationConfig

Example:

result = QueryMutationConfig.default()

Returns: QueryMutationConfig


QueryOnlyConfig

Configuration for schemas with only Query type

Field Type Default Description
introspection_enabled bool True Enable introspection queries
complexity_limit int \| None None Maximum query complexity (None = unlimited)
depth_limit int \| None None Maximum query depth (None = unlimited)
Methods
default()

Signature:

@staticmethod
def default() -> QueryOnlyConfig

Example:

result = QueryOnlyConfig.default()

Returns: QueryOnlyConfig


RateLimitConfig

Rate limiting configuration shared across runtimes

Field Type Default Description
per_second int 100 Requests per second
burst int 200 Burst allowance
ip_based bool True Use IP-based rate limiting
Methods
default()

Signature:

@staticmethod
def default() -> RateLimitConfig

Example:

result = RateLimitConfig.default()

Returns: RateLimitConfig


Request


Response

HTTP Response with custom status code, headers, and content

Field Type Default Description
content dict\[str, Any\] \| None None Response body content
status_code int HTTP status code (defaults to 200)
headers dict\[str, str\] {} Response headers
Methods
set_header()

Set a header

Signature:

def set_header(self, key: str, value: str) -> None

Example:

instance.set_header("value", "value")

Parameters:

Name Type Required Description
key str Yes The key
value str Yes The value

Returns: No return value.

Set a cookie in the response

Signature:

def set_cookie(self, key: str, value: str, secure: bool, http_only: bool, max_age: int, domain: str, path: str, same_site: str) -> None

Example:

instance.set_cookie("value", "value", True, True, max_age=42, domain="value", path="value", same_site="value")

Parameters:

Name Type Required Description
key str Yes The key
value str Yes The value
secure bool Yes The secure
http_only bool Yes The http only
max_age int \| None No The max age
domain str \| None No The domain
path str \| None No Path to the file
same_site str \| None No The same site

Returns: No return value.

default()

Signature:

@staticmethod
def default() -> Response

Example:

result = Response.default()

Returns: Response


ResponseSnapshot

Snapshot of an Axum response used by higher-level language bindings.

Field Type Default Description
status int HTTP status code.
headers dict\[str, str\] Response headers (lowercase keys for predictable lookups).
body bytes Response body bytes (decoded for supported encodings).
Methods
text()

Return response body as UTF-8 string.

Signature:

def text(self) -> str

Example:

result = instance.text()

Returns: str

Errors: Raises FromUtf8Error.

Lookup header by case-insensitive name.

Signature:

def header(self, name: str) -> str | None

Example:

result = instance.header("value")

Parameters:

Name Type Required Description
name str Yes The name

Returns: str | None


RouteBuilder

Builder for defining a route.

Methods
new()

Create a new builder for the provided HTTP method and path.

Signature:

@staticmethod
def new(method: Method, path: str) -> RouteBuilder

Example:

result = RouteBuilder.new(Method(), "value")

Parameters:

Name Type Required Description
method Method Yes The method
path str Yes Path to the file

Returns: RouteBuilder

handler_name()

Assign an explicit handler name.

Signature:

def handler_name(self, name: str) -> RouteBuilder

Example:

result = instance.handler_name("value")

Parameters:

Name Type Required Description
name str Yes The name

Returns: RouteBuilder

request_schema_json()

Provide a raw JSON schema for the request body.

Signature:

def request_schema_json(self, schema: dict[str, Any]) -> RouteBuilder

Example:

result = instance.request_schema_json({})

Parameters:

Name Type Required Description
schema dict\[str, Any\] Yes The schema

Returns: RouteBuilder

response_schema_json()

Provide a raw JSON schema for the response body.

Signature:

def response_schema_json(self, schema: dict[str, Any]) -> RouteBuilder

Example:

result = instance.response_schema_json({})

Parameters:

Name Type Required Description
schema dict\[str, Any\] Yes The schema

Returns: RouteBuilder

params_schema_json()

Provide a raw JSON schema for request parameters.

Signature:

def params_schema_json(self, schema: dict[str, Any]) -> RouteBuilder

Example:

result = instance.params_schema_json({})

Parameters:

Name Type Required Description
schema dict\[str, Any\] Yes The schema

Returns: RouteBuilder

file_params_json()

Provide multipart file parameter configuration.

Signature:

def file_params_json(self, schema: dict[str, Any]) -> RouteBuilder

Example:

result = instance.file_params_json({})

Parameters:

Name Type Required Description
schema dict\[str, Any\] Yes The schema

Returns: RouteBuilder

cors()

Attach a CORS configuration for this route.

Signature:

def cors(self, cors: CorsConfig) -> RouteBuilder

Example:

result = instance.cors(CorsConfig())

Parameters:

Name Type Required Description
cors CorsConfig Yes The cors config

Returns: RouteBuilder

compression()

Attach a compression configuration for this route.

Signature:

def compression(self, compression: CompressionConfig) -> RouteBuilder

Example:

result = instance.compression(CompressionConfig())

Parameters:

Name Type Required Description
compression CompressionConfig Yes The compression config

Returns: RouteBuilder

body_limit()

Attach a per-route maximum request body size in bytes, overriding the server-global default.

Signature:

def body_limit(self, max_bytes: int) -> RouteBuilder

Example:

result = instance.body_limit(42)

Parameters:

Name Type Required Description
max_bytes int Yes The max bytes

Returns: RouteBuilder

request_timeout()

Attach a per-route request timeout in seconds, overriding the server-global default.

Signature:

def request_timeout(self, seconds: int) -> RouteBuilder

Example:

result = instance.request_timeout(42)

Parameters:

Name Type Required Description
seconds int Yes The seconds

Returns: RouteBuilder

sync()

Mark the route as synchronous.

Signature:

def sync(self) -> RouteBuilder

Example:

result = instance.sync()

Returns: RouteBuilder

handler_dependencies()

Declare the dependency keys that must be resolved before this handler runs.

Signature:

def handler_dependencies(self, dependencies: list[str]) -> RouteBuilder

Example:

result = instance.handler_dependencies([])

Parameters:

Name Type Required Description
dependencies list\[str\] Yes The dependencies

Returns: RouteBuilder


SchemaConfig

Configuration for GraphQL schema building.

Encapsulates all schema-level configuration options including introspection control, complexity limits, and depth limits.

Field Type Default Description
introspection_enabled bool True Enable introspection queries
complexity_limit int \| None None Maximum query complexity (None = unlimited)
depth_limit int \| None None Maximum query depth (None = unlimited)
Methods
default()

Signature:

@staticmethod
def default() -> SchemaConfig

Example:

result = SchemaConfig.default()

Returns: SchemaConfig


ServerConfig

Server configuration

Field Type Default Description
host str "127.0.0.1" Host to bind to
port int 8000 Port to bind to
workers int 1 Number of Tokio runtime worker threads used by binding-managed server runtimes
enable_request_id bool False Enable request ID generation and propagation
max_body_size int \| None 10485760 Maximum request body size in bytes (None = unlimited, not recommended)
request_timeout int \| None None Request timeout in seconds (None = no timeout)
compression CompressionConfig \| None None Enable compression middleware
rate_limit RateLimitConfig \| None None Enable rate limiting
jwt_auth JwtConfig \| None None JWT authentication configuration
api_key_auth ApiKeyConfig \| None None API Key authentication configuration
static_files list\[StaticFilesConfig\] \[\] Static file serving configuration
graceful_shutdown bool True Enable graceful shutdown on SIGTERM/SIGINT
shutdown_timeout int 30 Graceful shutdown timeout (seconds)
asyncapi AsyncApiConfig \| None None AsyncAPI HTTP endpoint configuration
openapi OpenApiConfig \| None None OpenAPI documentation configuration
jsonrpc JsonRpcConfig \| None None JSON-RPC configuration
grpc GrpcConfig \| None None gRPC configuration
background_tasks BackgroundTaskConfig Background task executor configuration
enable_http_trace bool False Enable per-request HTTP tracing (tower-http TraceLayer)
Methods
default()

Signature:

@staticmethod
def default() -> ServerConfig

Example:

result = ServerConfig.default()

Returns: ServerConfig


ServerInfo

Server information

Field Type Default Description
url str Base URL of the server (e.g. "<https://api.example.com/v1">).
description str \| None None Optional human-readable description of the server environment.

SseEvent

An individual SSE event

Represents a single Server-Sent Event to be sent to a connected client. Events can have an optional type, ID, and retry timeout for advanced scenarios.

SSE Format

Events are serialized to the following text format:

event: event_type
data: {"json":"value"}
id: event-123
retry: 3000
Field Type Default Description
event_type str \| None None Event type (optional)
data dict\[str, Any\] Event data (JSON value)
id str \| None None Event ID (optional, for client-side reconnection)
retry int \| None None Retry timeout in milliseconds (optional)
Methods
with_id()

Set the event ID for client-side reconnection support

Sets an ID that clients can use to resume from this point if they disconnect. The client sends this ID back in the Last-Event-ID header when reconnecting.

Signature:

def with_id(self, id: str) -> SseEvent

Example:

result = instance.with_id("value")

Parameters:

Name Type Required Description
id str Yes Unique identifier for this event

Returns: SseEvent

with_retry()

Set the retry timeout for client reconnection

Sets the time in milliseconds clients should wait before attempting to reconnect if the connection is lost. The client browser will automatically handle reconnection.

Signature:

def with_retry(self, retry_ms: int) -> SseEvent

Example:

result = instance.with_retry(42)

Parameters:

Name Type Required Description
retry_ms int Yes Retry timeout in milliseconds

Returns: SseEvent


StaticFilesConfig

Static file serving configuration

Field Type Default Description
directory str Directory path to serve
route_prefix str URL path prefix (e.g., "/static")
index_file bool serde(default = "default_true") Fallback to index.html for directories
cache_control str \| None None Cache-Control header value

TestClient

Core test client for making HTTP requests to a Spikard application.

This struct wraps axum-test's TestServer and provides a language-agnostic interface for making HTTP requests, sending WebSocket connections, and handling Server-Sent Events. Language bindings wrap this to provide native API surfaces.

Methods
graphql_at()

Send a GraphQL query/mutation to a custom endpoint

Signature:

def graphql_at(self, endpoint: str, query: str, variables: dict[str, Any], operation_name: str) -> ResponseSnapshot

Example:

result = instance.graphql_at("value", "value", variables={}, operation_name="value")

Parameters:

Name Type Required Description
endpoint str Yes The endpoint
query str Yes The query
variables dict\[str, Any\] \| None No The variables
operation_name str \| None No The operation name

Returns: ResponseSnapshot

Errors: Raises SnapshotError.

graphql()

Send a GraphQL query/mutation

Signature:

def graphql(self, query: str, variables: dict[str, Any], operation_name: str) -> ResponseSnapshot

Example:

result = instance.graphql("value", variables={}, operation_name="value")

Parameters:

Name Type Required Description
query str Yes The query
variables dict\[str, Any\] \| None No The variables
operation_name str \| None No The operation name

Returns: ResponseSnapshot

Errors: Raises SnapshotError.

graphql_subscription_at()

Send a GraphQL subscription (WebSocket) to a custom endpoint.

Uses the graphql-transport-ws protocol and captures the first next payload. After the first payload is received, this client sends complete to unsubscribe.

Signature:

def graphql_subscription_at(self, endpoint: str, query: str, variables: dict[str, Any], operation_name: str) -> GraphQlSubscriptionSnapshot

Example:

result = instance.graphql_subscription_at("value", "value", variables={}, operation_name="value")

Parameters:

Name Type Required Description
endpoint str Yes The endpoint
query str Yes The query
variables dict\[str, Any\] \| None No The variables
operation_name str \| None No The operation name

Returns: GraphQlSubscriptionSnapshot

Errors: Raises SnapshotError.

graphql_subscription()

Send a GraphQL subscription (WebSocket).

Uses /graphql as the default subscription endpoint.

Signature:

def graphql_subscription(self, query: str, variables: dict[str, Any], operation_name: str) -> GraphQlSubscriptionSnapshot

Example:

result = instance.graphql_subscription("value", variables={}, operation_name="value")

Parameters:

Name Type Required Description
query str Yes The query
variables dict\[str, Any\] \| None No The variables
operation_name str \| None No The operation name

Returns: GraphQlSubscriptionSnapshot

Errors: Raises SnapshotError.


TestingSseEvent

A single Server-Sent Event.

Field Type Default Description
data str The data field of the event.

UploadFile

Represents an uploaded file from multipart/form-data requests.

This struct provides efficient access to file content with automatic base64 decoding and implements standard I/O traits for compatibility.

Field Type Default Description
filename str Original filename from the client
content_type str \| None None MIME type of the uploaded file
size int \| None None Size of the file in bytes
content bytes File content (may be base64 encoded)
content_encoding str \| None None Content encoding type
Methods
as_bytes()

Get the raw file content as bytes.

This provides zero-copy access to the underlying buffer.

Signature:

def as_bytes(self) -> bytes

Example:

result = instance.as_bytes()

Returns: bytes

read_to_string()

Read the file content as a UTF-8 string.

Errors:

Returns an error if the content is not valid UTF-8.

Signature:

def read_to_string(self) -> str

Example:

result = instance.read_to_string()

Returns: str

Errors: Raises Error.

content_type_or_default()

Get the content type, defaulting to "application/octet-stream".

Signature:

def content_type_or_default(self) -> str

Example:

result = instance.content_type_or_default()

Returns: str


ValidateRequest

Request body for POST /asyncapi/validate

Field Type Default Description
spec dict\[str, Any\] Spec
channel str Channel
message str Message
payload dict\[str, Any\] Payload

ValidationResponse

Response body for POST /asyncapi/validate

Field Type Default Description
valid bool Valid
errors list\[str\] Errors

Enums

Method

HTTP method

Value Description
GET Get
POST Post
PUT Put
PATCH Patch
DELETE Delete
HEAD Head
OPTIONS Options
CONNECT Connect
TRACE Trace

SecuritySchemeInfo

Security scheme types

Value Description
HTTP Http — Fields: scheme: str, bearer_format: str
API_KEY Api key — Fields: location: str, name: str

SnapshotError

Possible errors while converting an Axum response into a snapshot.

Value Description
INVALID_HEADER Response header could not be decoded to UTF-8. — Fields: 0: str
DECOMPRESSION Body decompression failed. — Fields: 0: str

WebSocketMessage

A WebSocket message that can be text or binary.

Value Description
TEXT A text message. — Fields: 0: str
BINARY A binary message. — Fields: 0: bytes
CLOSE A close message with a numeric close code (RFC 6455) and optional reason text. Common codes: 1000 Normal Closure, 1001 Going Away, 1005 No Status Received, 1006 Abnormal Closure. — Fields: code: int, reason: str
PING A ping message. — Fields: 0: bytes
PONG A pong message. — Fields: 0: bytes

Errors

AppError

Error type for application builder operations.

Base class: AppError(Exception)

Exception Description
Route(AppError) Route registration failed.
Server(AppError) Server/router construction failed.
Decode(AppError) Failed to extract DTO from the request context.
GraphQl(AppError) GraphQL route registration failed (e.g. an unrecognized schema_type).

GraphQlError

Errors that can occur during GraphQL operations

These errors are compatible with async-graphql error handling and can be converted to structured HTTP responses matching the project's error fixtures.

Base class: GraphQlError(Exception)

Exception Description
ExecutionError(GraphQlError) Error during schema execution Occurs when the GraphQL executor encounters a runtime error during query execution.
SchemaBuildError(GraphQlError) Error during schema building Occurs when schema construction fails due to invalid definitions or conflicts.
RequestHandlingError(GraphQlError) Error during request handling Occurs when the HTTP request cannot be properly handled or parsed.
SerializationError(GraphQlError) Serialization error Occurs during JSON serialization/deserialization of GraphQL values.
JsonError(GraphQlError) JSON parsing error Occurs when JSON input cannot be parsed.
ValidationError(GraphQlError) GraphQL validation error Occurs when a GraphQL query fails schema validation.
ParseError(GraphQlError) GraphQL parse error Occurs when the GraphQL query string cannot be parsed.
AuthenticationError(GraphQlError) Authentication error Occurs when request authentication fails.
AuthorizationError(GraphQlError) Authorization error Occurs when user lacks required permissions.
NotFound(GraphQlError) Not found error Occurs when a requested resource is not found.
RateLimitExceeded(GraphQlError) Rate limit error Occurs when rate limit is exceeded.
InvalidInput(GraphQlError) Invalid input error with validation details Occurs during input validation with detailed error information.
ComplexityLimitExceeded(GraphQlError) Query complexity limit exceeded Occurs when a GraphQL query exceeds the configured complexity limit.
DepthLimitExceeded(GraphQlError) Query depth limit exceeded Occurs when a GraphQL query exceeds the configured depth limit.
IntrospectionDisabled(GraphQlError) Introspection query rejected because introspection is disabled Occurs when a query selects __schema or __type while the schema was configured with introspection disabled.
InternalError(GraphQlError) Internal server error Occurs when an unexpected internal error happens.

SchemaError

Error type for schema building operations

Base class: SchemaError(Exception)

Exception Description
BuildingFailed(SchemaError) Generic schema building error
ValidationError(SchemaError) Configuration validation error
ComplexityLimitExceeded(SchemaError) Complexity limit exceeded
DepthLimitExceeded(SchemaError) Depth limit exceeded

Edit this page on GitHub