Skip to content

Zig API Reference

Zig API Reference v0.17.0

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:

pub fn schema_query_only() []u8

Example:

const result = schema_query_only();

Returns: []u8


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:

pub fn schema_query_mutation() []u8

Example:

const result = schema_query_mutation();

Returns: []u8


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:

pub fn schema_full() []u8

Example:

const result = schema_full();

Returns: []u8


Types

ApiKeyAuthConfig

Per-route API key authentication requirement.

Mirrors spikard_http.ApiKeyConfig for the same reason JwtAuthConfig mirrors spikard_http.JwtConfig: spikard-core cannot depend on spikard-http.

Field Type Default Description
enabled bool true Whether this per-route API key auth requirement is active. Present on 10/10 api_key_auth fixture payloads in the corpus; defaults to true for the same reason as JwtAuthConfig.enabled.
keys \[\]const \[\]const u8 /* serde(default) */ Valid API keys. Defaults to empty (rather than being a required field) so that fixtures/server_config.json's server_jwt_and_api_key_auth_combined payload ({"enabled": true, "header": "X-API-Key"}, no keys at all) deserializes instead of hard-failing with "missing field keys". An empty list is NOT "allow everyone": a later enforcement phase MUST treat an empty keys list as a hard misconfiguration error, never as an open gate.
header_name \[\]const u8 "X-API-Key" Header name to check (e.g., "X-API-Key")

ApiKeyConfig

API Key authentication configuration

Field Type Default Description
keys \[\]const \[\]const u8 Valid API keys
header_name \[\]const u8 "X-API-Key" 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 \[\]const u8? null Pre-registered AsyncAPI spec to serve from GET /asyncapi.json

AuthorizationConfig

Per-route roles/scopes/permissions authorization requirement.

spikard_http.auth.Claims does not yet carry roles, scopes, or permissions, so nothing can enforce this today. This type only defines the requirement shape; a later phase must extend Claims (or an equivalent claims-decoding path) to populate them before enforcement is possible.

Deserialization goes through AuthorizationConfigRepr rather than a derive so the fixture's singular {"required_role": "admin"} shape (fixtures/problem_details.json's problem_details_403_forbidden) populates required_roles instead of being silently dropped as an unrecognized field — a config that parses to "no constraint" from real authorization data is a vacuous-pass bug, not a compatibility shim. deny_unknown_fields on the repr means any other unrecognized key is a loud deserialize error instead.

Field Type Default Description
required_roles \[\]const \[\]const u8 [] Roles the authenticated caller must have
required_scopes \[\]const \[\]const u8 [] OAuth-style scopes the authenticated caller must have
required_permissions \[\]const \[\]const u8 [] Fine-grained permissions the authenticated caller must have
require_all bool true When true, the caller must satisfy every listed requirement (AND); when false, any single listed requirement is sufficient (OR)

BackgroundJobMetadata

Field Type Default Description
name \[\]const u8 "background_task" The name
request_id \[\]const u8? null Request id

BackgroundTaskConfig

Configuration for in-process background task execution.

Field Type Default Description
enabled bool false Whether the server starts a background task executor at router-construction time. ServerConfig.background_tasks is a bare struct rather than an Option, so its mere presence cannot mean "configured" the way Option-shaped middleware config does — every server has one. Without this flag every router build would spawn an executor task, which also requires an ambient Tokio runtime that a synchronous build_router_* caller may not have. Defaults to false so opting in is explicit, and matches the corpus vocabulary: fixtures/background_tasks.json spells its per-route payloads {"enabled": true, ...}.
max_queue_size u64 1024 Maximum queue size
max_concurrent_tasks u64 128 Maximum concurrent tasks
drain_timeout_secs u64 30 Drain timeout secs

CompressionConfig

Compression configuration shared across runtimes

Field Type Default Description
gzip bool true Enable gzip compression
brotli bool true Enable brotli compression
min_size u64 1024 Minimum response size to compress (bytes)
quality u32 6 Compression quality (0-11 for brotli, 0-9 for gzip)

ContactInfo

Contact information

Field Type Default Description
name \[\]const u8? null Name of the contact person or organisation.
email \[\]const u8? null Contact email address.
url \[\]const u8? null URL pointing to the contact information page.

CorsConfig

CORS configuration for a route

Field Type Default Description
allowed_origins \[\]const \[\]const u8 ["*"] Allowed origins
allowed_methods \[\]const \[\]const u8 ["*"] Allowed methods
allowed_headers \[\]const \[\]const u8 [] Allowed headers
expose_headers \[\]const \[\]const u8? null Expose headers
max_age u32? null Maximum age
allow_credentials bool? null Allow credentials

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 u64? null Maximum query complexity (null = unlimited).
max_depth u64? null Maximum query depth (null = unlimited).
field_errors \[\]const 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 \[\]const u8 Dot-separated path to the field that should error.
message \[\]const u8 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 u64? null Maximum query complexity (None = unlimited)
depth_limit u64? null Maximum query depth (None = unlimited)

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:

pub fn new_graph_ql_route_config() GraphQLRouteConfig

Example:

const result = new_graph_ql_route_config();

Returns: GraphQLRouteConfig

path()

Set the HTTP path for the GraphQL endpoint

Signature:

pub fn path(self: *const GraphQlRouteConfig, path: []const u8) GraphQLRouteConfig

Example:

const result = instance.path("value");

Parameters:

Name Type Required Description
path \[\]const u8 Yes The URL path (e.g., "/graphql", "/api/graphql")

Returns: GraphQLRouteConfig

method()

Set the HTTP method for the GraphQL endpoint

Signature:

pub fn method(self: *const GraphQlRouteConfig, method: []const u8) GraphQLRouteConfig

Example:

const result = instance.method("value");

Parameters:

Name Type Required Description
method \[\]const u8 Yes The HTTP method (typically "POST")

Returns: GraphQLRouteConfig

enable_playground()

Enable or disable the GraphQL Playground UI

Signature:

pub fn enable_playground(self: *const GraphQlRouteConfig, enable: bool) GraphQLRouteConfig

Example:

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

pub fn description(self: *const GraphQlRouteConfig, description: []const u8) GraphQLRouteConfig

Example:

const result = instance.description("value");

Parameters:

Name Type Required Description
description \[\]const u8 Yes Documentation string

Returns: GraphQLRouteConfig

get_path()

Get the configured path

Signature:

pub fn get_path(self: *const GraphQlRouteConfig) []u8

Example:

const result = instance.get_path();

Returns: []u8

get_method()

Get the configured method

Signature:

pub fn get_method(self: *const GraphQlRouteConfig) []u8

Example:

const result = instance.get_method();

Returns: []u8

is_playground_enabled()

Check if playground is enabled

Signature:

pub fn is_playground_enabled(self: *const GraphQlRouteConfig) bool

Example:

const result = instance.is_playground_enabled();

Returns: bool

get_description()

Get the description if set

Signature:

pub fn get_description(self: *const GraphQlRouteConfig) ?[]u8

Example:

const result = instance.get_description();

Returns: ?[]u8


GraphQlSubscriptionSnapshot

Snapshot of a GraphQL subscription exchange over WebSocket.

Derives Serialize so language bindings (e.g. the JNI backend) can marshal it across the FFI boundary via serde_json without a hand-written wrapper.

Field Type Default Description
operation_id \[\]const u8 Operation id used for the subscription request.
acknowledged bool Whether the server acknowledged the GraphQL WebSocket connection.
event \[\]const u8? null First next.payload received for this subscription, if any.
errors \[\]const \[\]const u8 [] 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 null (unbounded).

Field Type Default Description
enabled bool true Enable gRPC support
max_message_size u64 4194304 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 u64? null Timeout for gRPC requests in seconds (None = no timeout)
max_concurrent_streams u32 100 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 u64 75 HTTP/2 keepalive interval in seconds
keepalive_timeout u64 20 HTTP/2 keepalive timeout in seconds
max_stream_response_bytes u64? null 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: null (unbounded total response size).

IntoHandler

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

Methods
into_handler()

Convert this value into a shared request handler.

Signature:

pub fn into_handler(self: *const IntoHandler) Handler

Example:

const result = instance.into_handler();

Returns: Handler


JsonRpcConfig

JSON-RPC server configuration

Field Type Default Description
enabled bool true Enable JSON-RPC endpoint
endpoint_path \[\]const u8 "/rpc" HTTP endpoint path for JSON-RPC requests (default: "/rpc")
enable_batch bool true Enable batch request processing (default: true)
max_batch_size u64 100 Maximum number of requests in a batch (default: 100)

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 \[\]const u8 The JSON-RPC method name (e.g., "user.create")
description \[\]const u8? null Optional description of what the method does
params_schema \[\]const u8? null Optional JSON Schema for method parameters
result_schema \[\]const u8? null Optional JSON Schema for the result
deprecated bool /* serde(default) */ Whether this method is deprecated
tags \[\]const \[\]const u8 /* serde(default) */ Tags for categorizing and grouping methods

JwtAuthConfig

Per-route JWT authentication requirement.

spikard-http defines the canonical JwtConfig used by ServerConfig.jwt_auth, but spikard-core cannot depend on spikard-http (the dependency runs the other way), so that type cannot be reused here. This mirrors its fields so a later enforcement phase in spikard-http can convert between the two without losing information.

secret and public_key are both optional because asymmetric algorithms (RS256, ES256, ...) verify against a public key rather than a shared secret; see fixtures/auth.json's jwt_config_algorithm_rs256, which carries public_key and no secret at all. Exactly one is expected to be populated for a given algorithm, but that cross-field invariant is left to a later enforcement phase rather than the type itself.

Field Type Default Description
enabled bool true Whether this per-route JWT auth requirement is active. Present on 21/21 jwt_auth fixture payloads in the corpus; defaults to true because presence of a jwt_auth block has always meant "enabled" up to now. Without this field a fixture setting "enabled": false would silently keep auth on while the fixture's parse still succeeds — a vacuous pass.
secret \[\]const u8? /* serde(default) */ Symmetric secret key for JWT verification (HS256, HS384, HS512)
public_key \[\]const u8? /* serde(default) */ Asymmetric public key for JWT verification (RS256, ES256, etc.)
algorithm \[\]const u8 "HS256" Required algorithm (HS256, HS384, HS512, RS256, etc.)
audience \[\]const \[\]const u8? null Required audience claim
issuer \[\]const u8? null Required issuer claim
leeway u64 /* serde(default) */ Leeway for expiration checks (seconds)

JwtConfig

JWT authentication configuration

Field Type Default Description
secret \[\]const u8 Secret key for JWT verification
algorithm \[\]const u8 "HS256" Required algorithm (HS256, HS384, HS512, RS256, etc.)
audience \[\]const \[\]const u8? null Required audience claim
issuer \[\]const u8? null Required issuer claim
leeway u64 /* serde(default) */ Leeway for expiration checks (seconds)

LicenseInfo

License information

Field Type Default Description
name \[\]const u8 SPDX license identifier or display name (e.g. "MIT").
url \[\]const u8? null URL to the full license text.

LifecycleHookRef

A single lifecycle hook reference within a LifecycleHooksConfig phase.

Matches the fixture shape exactly (fixtures/lifecycle_hooks.json, fixtures/di.json): each entry is an object with a required name and handler, an optional list of dependency keys, and an optional free-form config blob (e.g. {"max_requests": 10, "window_seconds": 60} for a rate-limiting hook). deny_unknown_fields turns future fixture drift into a loud error.

Field Type Default Description
name \[\]const u8 Registered name of the hook to run, resolved against the server's LifecycleHooks
handler \[\]const u8 Name of the handler function this hook invokes
dependencies \[\]const \[\]const u8 [] Dependency keys this hook requires (for DI), resolved before the hook runs
config \[\]const u8? null Optional free-form configuration passed to the hook (e.g. rate-limit thresholds)
order u32? null Explicit execution order within the phase, where the corpus states one (fixtures/lifecycle_hooks.json's hook_execution_order). Array position already implies an order, so this exists to let a fixture assert ordering rather than rely on it.

LifecycleHooksConfig

Per-route selection of registered lifecycle hooks.

ServerConfig.lifecycle_hooks holds Arc<dyn LifecycleHook> function pointers and is marked #[serde(skip)] / #[alef(skip)] because closures cannot be serialized or cross the FFI boundary. A per-route field with that same shape would be invisible to alef, and therefore invisible to every binding — defeating the purpose of exposing it here. This descriptor carries LifecycleHookRef entries instead: each one names a registered hook (plus its declared dependencies and optional config), so a later enforcement phase can resolve those names against the server's registered LifecycleHooks and run the matches for this route. The five fields mirror the five hook phases documented in the tower-middleware-and-lifecycle project convention (onRequest, preValidation, preHandler, onResponse, onError).

Field Type Default Description
on_request \[\]const LifecycleHookRef [] Hooks to run in the on_request phase
pre_validation \[\]const LifecycleHookRef [] Hooks to run in the pre_validation phase
pre_handler \[\]const LifecycleHookRef [] Hooks to run in the pre_handler phase
on_response \[\]const LifecycleHookRef [] Hooks to run in the on_response phase
on_error \[\]const LifecycleHookRef [] Hooks to run in the on_error phase

OpenApiConfig

OpenAPI configuration

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

ParseRequest

Request body for POST /asyncapi/parse

Field Type Default Description
spec \[\]const u8 Spec

ParseResult

Full parse result returned by POST /asyncapi/parse

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

ParsedChannel

A single channel extracted from an AsyncAPI spec

Field Type Default Description
name \[\]const u8 Channel key from the spec (e.g. "chat/messages")
address \[\]const u8 Channel address / path
messages \[\]const \[\]const u8 Message names declared on this channel
bindings \[\]const u8? null Bindings (ws / http / amqp / …) as raw JSON for forward-compatibility

ParsedMessage

A resolved message (name + JSON Schema)

Field Type Default Description
name \[\]const u8 Message name
schema \[\]const u8? null Resolved JSON Schema for the message payload, if available

ParsedOperation

A single operation extracted from an AsyncAPI spec

Field Type Default Description
name \[\]const u8 Operation name
action \[\]const u8 Operation action: "send" or "receive"
channel \[\]const u8 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 \[\]const u8 "about:blank" 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 \[\]const u8 "" A short, human-readable summary of the problem type. Should not change from occurrence to occurrence of the problem.
status u16 500 The HTTP status code generated by the origin server. This is advisory; the actual HTTP status code takes precedence.
detail \[\]const u8? null A human-readable explanation specific to this occurrence of the problem.
instance \[\]const u8? null A URI reference that identifies the specific occurrence of the problem. It may or may not yield further information if dereferenced.
extensions std.StringHashMap(\[\]const u8) {} Extension members - problem-type-specific data. For validation errors, this typically contains an "errors" array.

QueryMutationConfig

Configuration for schemas with Query and Mutation types

Field Type Default Description
introspection_enabled bool true Enable introspection queries
complexity_limit u64? null Maximum query complexity (None = unlimited)
depth_limit u64? null Maximum query depth (None = unlimited)

QueryOnlyConfig

Configuration for schemas with only Query type

Field Type Default Description
introspection_enabled bool true Enable introspection queries
complexity_limit u64? null Maximum query complexity (None = unlimited)
depth_limit u64? null Maximum query depth (None = unlimited)

RateLimitConfig

Rate limiting configuration shared across runtimes

Field Type Default Description
per_second u64 100 Requests per second
burst u32 200 Burst allowance
ip_based bool true Use IP-based rate limiting

Request


RequestIdConfig

Per-route request-id generation/propagation override.

Modeled as a struct rather than Option<bool> on RouteMetadata because the wire shape is an object, not a bare boolean: fixtures/request_id.json's request_id_middleware_can_be_disabled sends {"enabled": false}, which Option<bool> cannot deserialize at all ("invalid type: map, expected a boolean") — the very fixture whose purpose is proving the middleware can be disabled was the one that failed to parse.

Field Type Default Description
enabled bool Whether request-id generation/propagation is active for this route

Response

HTTP Response with custom status code, headers, and content

Field Type Default Description
content \[\]const u8? null Response body content
status_code u16 200 HTTP status code (defaults to 200)
headers std.StringHashMap(\[\]const u8) {} Response headers

ResponseSnapshot

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

Field Type Default Description
status u16 HTTP status code.
headers std.StringHashMap(\[\]const u8) Response headers (lowercase keys for predictable lookups).
body \[\]const u8 Response body bytes (decoded for supported encodings).

RouteBuilder

Builder for defining a route.

Methods
new()

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

Signature:

pub fn new_route_builder(method: Method, path: []const u8) RouteBuilder

Example:

const result = new_route_builder(.{}, "value");

Parameters:

Name Type Required Description
method Method Yes The method
path \[\]const u8 Yes Path to the file

Returns: RouteBuilder

handler_name()

Assign an explicit handler name.

Signature:

pub fn handler_name(self: *const RouteBuilder, name: []const u8) RouteBuilder

Example:

const result = instance.handler_name("value");

Parameters:

Name Type Required Description
name \[\]const u8 Yes The name

Returns: RouteBuilder

request_schema_json()

Provide a raw JSON schema for the request body.

Signature:

pub fn request_schema_json(self: *const RouteBuilder, schema: []const u8) RouteBuilder

Example:

const result = instance.request_schema_json(.{});

Parameters:

Name Type Required Description
schema \[\]const u8 Yes The schema

Returns: RouteBuilder

response_schema_json()

Provide a raw JSON schema for the response body.

Signature:

pub fn response_schema_json(self: *const RouteBuilder, schema: []const u8) RouteBuilder

Example:

const result = instance.response_schema_json(.{});

Parameters:

Name Type Required Description
schema \[\]const u8 Yes The schema

Returns: RouteBuilder

params_schema_json()

Provide a raw JSON schema for request parameters.

Signature:

pub fn params_schema_json(self: *const RouteBuilder, schema: []const u8) RouteBuilder

Example:

const result = instance.params_schema_json(.{});

Parameters:

Name Type Required Description
schema \[\]const u8 Yes The schema

Returns: RouteBuilder

file_params_json()

Provide multipart file parameter configuration.

Signature:

pub fn file_params_json(self: *const RouteBuilder, schema: []const u8) RouteBuilder

Example:

const result = instance.file_params_json(.{});

Parameters:

Name Type Required Description
schema \[\]const u8 Yes The schema

Returns: RouteBuilder

cors()

Attach a CORS configuration for this route.

Signature:

pub fn cors(self: *const RouteBuilder, cors: []const u8) RouteBuilder

Example:

const result = instance.cors(.{});

Parameters:

Name Type Required Description
cors \[\]const u8 Yes The cors config

Returns: RouteBuilder

compression()

Attach a compression configuration for this route.

Signature:

pub fn compression(self: *const RouteBuilder, compression: []const u8) RouteBuilder

Example:

const result = instance.compression(.{});

Parameters:

Name Type Required Description
compression \[\]const u8 Yes The compression config

Returns: RouteBuilder

body_limit()

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

Signature:

pub fn body_limit(self: *const RouteBuilder, max_bytes: u64) RouteBuilder

Example:

const result = instance.body_limit(42);

Parameters:

Name Type Required Description
max_bytes u64 Yes The max bytes

Returns: RouteBuilder

request_timeout()

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

Signature:

pub fn request_timeout(self: *const RouteBuilder, seconds: u64) RouteBuilder

Example:

const result = instance.request_timeout(42);

Parameters:

Name Type Required Description
seconds u64 Yes The seconds

Returns: RouteBuilder

rate_limit()

Attach a per-route rate limiting configuration, overriding the server-global default.

Signature:

pub fn rate_limit(self: *const RouteBuilder, rate_limit: []const u8) RouteBuilder

Example:

const result = instance.rate_limit(.{});

Parameters:

Name Type Required Description
rate_limit \[\]const u8 Yes The rate limit config

Returns: RouteBuilder

request_id()

Force per-route request-id generation on or off, overriding the server-global default.

Takes a plain bool rather than RequestIdConfig directly: the wire/metadata type had to become a struct to represent {"enabled": false} (see RequestIdConfig's docs), but this builder is the ergonomic call site (.request_id(true)), so it keeps accepting a bool and wraps it into RequestIdConfig internally in Self.into_metadata.

Signature:

pub fn request_id(self: *const RouteBuilder, enabled: bool) RouteBuilder

Example:

const result = instance.request_id(true);

Parameters:

Name Type Required Description
enabled bool Yes The enabled

Returns: RouteBuilder

jwt_auth()

Require JWT authentication for this route.

Signature:

pub fn jwt_auth(self: *const RouteBuilder, config: []const u8) RouteBuilder

Example:

const result = instance.jwt_auth(.{});

Parameters:

Name Type Required Description
config \[\]const u8 Yes The configuration options

Returns: RouteBuilder

api_key_auth()

Require API key authentication for this route.

Signature:

pub fn api_key_auth(self: *const RouteBuilder, config: []const u8) RouteBuilder

Example:

const result = instance.api_key_auth(.{});

Parameters:

Name Type Required Description
config \[\]const u8 Yes The configuration options

Returns: RouteBuilder

authorization()

Attach a roles/scopes/permissions authorization requirement for this route.

Signature:

pub fn authorization(self: *const RouteBuilder, config: []const u8) RouteBuilder

Example:

const result = instance.authorization(.{});

Parameters:

Name Type Required Description
config \[\]const u8 Yes The configuration options

Returns: RouteBuilder

lifecycle_hooks()

Select registered lifecycle hooks to run for this route.

Signature:

pub fn lifecycle_hooks(self: *const RouteBuilder, hooks: []const u8) RouteBuilder

Example:

const result = instance.lifecycle_hooks(.{});

Parameters:

Name Type Required Description
hooks \[\]const u8 Yes The lifecycle hooks config

Returns: RouteBuilder

jsonrpc_method()

Expose this route as a JSON-RPC method.

Signature:

pub fn jsonrpc_method(self: *const RouteBuilder, info: []const u8) RouteBuilder

Example:

const result = instance.jsonrpc_method(.{});

Parameters:

Name Type Required Description
info \[\]const u8 Yes The json rpc method info

Returns: RouteBuilder

openrpc_spec()

Attach a literal OpenRPC method spec document for this route, overriding auto-derivation from the Self.jsonrpc_method metadata when present.

Signature:

pub fn openrpc_spec(self: *const RouteBuilder, spec: []const u8) RouteBuilder

Example:

const result = instance.openrpc_spec(.{});

Parameters:

Name Type Required Description
spec \[\]const u8 Yes The spec

Returns: RouteBuilder

sync()

Mark the route as synchronous.

Signature:

pub fn sync(self: *const RouteBuilder) RouteBuilder

Example:

const result = instance.sync();

Returns: RouteBuilder

handler_dependencies()

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

Signature:

pub fn handler_dependencies(self: *const RouteBuilder, dependencies: []const u8) RouteBuilder

Example:

const result = instance.handler_dependencies(&[_]u8{});

Parameters:

Name Type Required Description
dependencies \[\]const u8 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 u64? null Maximum query complexity (None = unlimited)
depth_limit u64? null Maximum query depth (None = unlimited)

ServerConfig

Server configuration

Field Type Default Description
host \[\]const u8 "127.0.0.1" Host to bind to
port u16 8000 Port to bind to
workers u64 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 u64? 10485760 Maximum request body size in bytes (None = unlimited, not recommended)
request_timeout u64? null Request timeout in seconds (None = no timeout)
compression CompressionConfig? null Enable compression middleware
rate_limit RateLimitConfig? null Enable rate limiting
jwt_auth JwtConfig? null JWT authentication configuration
api_key_auth ApiKeyConfig? null API Key authentication configuration
static_files \[\]const StaticFilesConfig [] Static file serving configuration
graceful_shutdown bool true Enable graceful shutdown on SIGTERM/SIGINT
shutdown_timeout u64 30 Graceful shutdown timeout (seconds)
asyncapi AsyncApiConfig? null AsyncAPI HTTP endpoint configuration
openapi OpenApiConfig? null OpenAPI documentation configuration
jsonrpc JsonRpcConfig? null JSON-RPC configuration
grpc GrpcConfig? null gRPC configuration
background_tasks BackgroundTaskConfig Background task executor configuration
enable_http_trace bool false Enable per-request HTTP tracing (tower-http TraceLayer)

ServerInfo

Server information

Field Type Default Description
url \[\]const u8 Base URL of the server (e.g. "<https://api.example.com/v1>").
description \[\]const u8? null 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 \[\]const u8? null Event type (optional)
data \[\]const u8 Event data (JSON value)
id \[\]const u8? null Event ID (optional, for client-side reconnection)
retry u64? null Retry timeout in milliseconds (optional)

StaticFilesConfig

Static file serving configuration

Field Type Default Description
directory \[\]const u8 Directory path to serve
route_prefix \[\]const u8 URL path prefix (e.g., "/static")
index_file bool true Fallback to index.html for directories
cache_control \[\]const u8? null 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:

pub fn graphql_at(self: *const TestClient, endpoint: []const u8, query: []const u8, variables: ?[]const u8, operation_name: ?[]const u8) SnapshotError![]u8

Example:

const result = try instance.graphql_at("value", "value", .{}, "value");

Parameters:

Name Type Required Description
endpoint \[\]const u8 Yes The endpoint
query \[\]const u8 Yes The query
variables ?\[\]const u8 No The variables
operation_name ?\[\]const u8 No The operation name

Returns: []u8

Errors: Throws SnapshotError.

graphql()

Send a GraphQL query/mutation

Signature:

pub fn graphql(self: *const TestClient, query: []const u8, variables: ?[]const u8, operation_name: ?[]const u8) SnapshotError![]u8

Example:

const result = try instance.graphql("value", .{}, "value");

Parameters:

Name Type Required Description
query \[\]const u8 Yes The query
variables ?\[\]const u8 No The variables
operation_name ?\[\]const u8 No The operation name

Returns: []u8

Errors: Throws 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:

pub fn graphql_subscription_at(self: *const TestClient, endpoint: []const u8, query: []const u8, variables: ?[]const u8, operation_name: ?[]const u8) SnapshotError!GraphQLSubscriptionSnapshot

Example:

const result = try instance.graphql_subscription_at("value", "value", .{}, "value");

Parameters:

Name Type Required Description
endpoint \[\]const u8 Yes The endpoint
query \[\]const u8 Yes The query
variables ?\[\]const u8 No The variables
operation_name ?\[\]const u8 No The operation name

Returns: GraphQLSubscriptionSnapshot

Errors: Throws SnapshotError.

graphql_subscription()

Send a GraphQL subscription (WebSocket).

Uses /graphql as the default subscription endpoint.

Signature:

pub fn graphql_subscription(self: *const TestClient, query: []const u8, variables: ?[]const u8, operation_name: ?[]const u8) SnapshotError!GraphQLSubscriptionSnapshot

Example:

const result = try instance.graphql_subscription("value", .{}, "value");

Parameters:

Name Type Required Description
query \[\]const u8 Yes The query
variables ?\[\]const u8 No The variables
operation_name ?\[\]const u8 No The operation name

Returns: GraphQLSubscriptionSnapshot

Errors: Throws SnapshotError.


TestingSseEvent

A single Server-Sent Event.

Field Type Default Description
data \[\]const u8 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 \[\]const u8 Original filename from the client
content_type \[\]const u8? null MIME type of the uploaded file
size u64? null Size of the file in bytes
content \[\]const u8 File content (may be base64 encoded)
content_encoding \[\]const u8? null Content encoding type

ValidateRequest

Request body for POST /asyncapi/validate

Field Type Default Description
spec \[\]const u8 Spec
channel \[\]const u8 Channel
message \[\]const u8 Message
payload \[\]const u8 Payload

ValidationResponse

Response body for POST /asyncapi/validate

Field Type Default Description
valid bool Valid
errors \[\]const \[\]const u8 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

LifecycleHookPhase

The five lifecycle phases a hook can be registered against.

Used to resolve a per-route named hook selection (LifecycleHooksConfig in spikard-core.http) against the hooks actually registered on the server: a name is looked up within one specific phase's registered hooks, not across all five, so a hook registered for on_response can never be silently picked up by a route asking for on_request.

Value Description
on_request On request
pre_validation Pre validation
pre_handler Pre handler
on_response On response
on_error On error

SecuritySchemeInfo

Security scheme types

Value Description
http Http — Fields: scheme: []const u8, bearer_format: []const u8
api_key Api key — Fields: location: []const u8, name: []const u8

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: []const u8
decompression Body decompression failed. — Fields: 0: []const u8

WebSocketMessage

A WebSocket message that can be text or binary.

Value Description
text A text message. — Fields: 0: []const u8
binary A binary message. — Fields: 0: []const u8
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: u16, reason: []const u8
ping A ping message. — Fields: 0: []const u8
pong A pong message. — Fields: 0: []const u8

Errors

AppError

Error type for application builder operations.

Variant Description
route Route registration failed.
server Server/router construction failed.
decode Failed to extract DTO from the request context.
graph_ql 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.

Variant Description
execution_error Error during schema execution Occurs when the GraphQL executor encounters a runtime error during query execution.
schema_build_error Error during schema building Occurs when schema construction fails due to invalid definitions or conflicts.
request_handling_error Error during request handling Occurs when the HTTP request cannot be properly handled or parsed.
serialization_error Serialization error Occurs during JSON serialization/deserialization of GraphQL values.
json_error JSON parsing error Occurs when JSON input cannot be parsed.
validation_error GraphQL validation error Occurs when a GraphQL query fails schema validation.
parse_error GraphQL parse error Occurs when the GraphQL query string cannot be parsed.
authentication_error Authentication error Occurs when request authentication fails.
authorization_error Authorization error Occurs when user lacks required permissions.
not_found Not found error Occurs when a requested resource is not found.
rate_limit_exceeded Rate limit error Occurs when rate limit is exceeded.
invalid_input Invalid input error with validation details Occurs during input validation with detailed error information.
complexity_limit_exceeded Query complexity limit exceeded Occurs when a GraphQL query exceeds the configured complexity limit.
depth_limit_exceeded Query depth limit exceeded Occurs when a GraphQL query exceeds the configured depth limit.
introspection_disabled Introspection query rejected because introspection is disabled Occurs when a query selects __schema or __type while the schema was configured with introspection disabled.
internal_error Internal server error Occurs when an unexpected internal error happens.

SchemaError

Error type for schema building operations

Variant Description
building_failed Generic schema building error
validation_error Configuration validation error
complexity_limit_exceeded Complexity limit exceeded
depth_limit_exceeded Depth limit exceeded

Edit this page on GitHub