Skip to content

WebAssembly API Reference

WebAssembly API Reference v0.17.0

Functions

schemaQueryOnly()

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:

function schemaQueryOnly(): QueryOnlyConfig

Example:

const result = schemaQueryOnly();

Returns: QueryOnlyConfig


schemaQueryMutation()

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:

function schemaQueryMutation(): QueryMutationConfig

Example:

const result = schemaQueryMutation();

Returns: QueryMutationConfig


schemaFull()

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:

function schemaFull(): FullSchemaConfig

Example:

const result = schemaFull();

Returns: FullSchemaConfig


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 boolean 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 Array<string> /* 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.
headerName string "X-API-Key" Header name to check (e.g., "X-API-Key")

ApiKeyConfig

API Key authentication configuration

Field Type Default Description
keys Array<string> Valid API keys
headerName string "X-API-Key" Header name to check (e.g., "X-API-Key")

AsyncApiConfig

AsyncAPI HTTP endpoint configuration

Field Type Default Description
enabled boolean Enable AsyncAPI endpoints (default: false)
spec unknown \| null 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
requiredRoles Array<string> [] Roles the authenticated caller must have
requiredScopes Array<string> [] OAuth-style scopes the authenticated caller must have
requiredPermissions Array<string> [] Fine-grained permissions the authenticated caller must have
requireAll boolean true When true, the caller must satisfy every listed requirement (AND); when false, any single listed requirement is sufficient (OR)

CompressionConfig

Compression configuration shared across runtimes

Field Type Default Description
gzip boolean true Enable gzip compression
brotli boolean true Enable brotli compression
minSize number 1024 Minimum response size to compress (bytes)
quality number 6 Compression quality (0-11 for brotli, 0-9 for gzip)

ContactInfo

Contact information

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

CorsConfig

CORS configuration for a route

Field Type Default Description
allowedOrigins Array<string> ["*"] Allowed origins
allowedMethods Array<string> ["*"] Allowed methods
allowedHeaders Array<string> [] Allowed headers
exposeHeaders Array<string> \| null null Expose headers
maxAge number \| null null Maximum age
allowCredentials boolean \| null null Allow credentials

IntoHandler

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

Methods
intoHandler()

Convert this value into a shared request handler.

Signature:

intoHandler(): Handler

Example:

const result = instance.intoHandler();

Returns: Handler


JsonRpcConfig

JSON-RPC server configuration

Field Type Default Description
enabled boolean true Enable JSON-RPC endpoint
endpointPath string "/rpc" HTTP endpoint path for JSON-RPC requests (default: "/rpc")
enableBatch boolean true Enable batch request processing (default: true)
maxBatchSize number 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
methodName string The JSON-RPC method name (e.g., "user.create")
description string \| null null Optional description of what the method does
paramsSchema unknown \| null null Optional JSON Schema for method parameters
resultSchema unknown \| null null Optional JSON Schema for the result
deprecated boolean /* serde(default) */ Whether this method is deprecated
tags Array<string> /* 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 boolean 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 string \| null /* serde(default) */ Symmetric secret key for JWT verification (HS256, HS384, HS512)
publicKey string \| null /* serde(default) */ Asymmetric public key for JWT verification (RS256, ES256, etc.)
algorithm string "HS256" Required algorithm (HS256, HS384, HS512, RS256, etc.)
audience Array<string> \| null null Required audience claim
issuer string \| null null Required issuer claim
leeway number /* serde(default) */ Leeway for expiration checks (seconds)

JwtConfig

JWT authentication configuration

Field Type Default Description
secret string Secret key for JWT verification
algorithm string "HS256" Required algorithm (HS256, HS384, HS512, RS256, etc.)
audience Array<string> \| null null Required audience claim
issuer string \| null null Required issuer claim
leeway number /* serde(default) */ Leeway for expiration checks (seconds)

LicenseInfo

License information

Field Type Default Description
name string SPDX license identifier or display name (e.g. "MIT").
url string \| null 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 string Registered name of the hook to run, resolved against the server's LifecycleHooks
handler string Name of the handler function this hook invokes
dependencies Array<string> [] Dependency keys this hook requires (for DI), resolved before the hook runs
config unknown \| null null Optional free-form configuration passed to the hook (e.g. rate-limit thresholds)
order number \| null 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
onRequest Array<LifecycleHookRef> [] Hooks to run in the on_request phase
preValidation Array<LifecycleHookRef> [] Hooks to run in the pre_validation phase
preHandler Array<LifecycleHookRef> [] Hooks to run in the pre_handler phase
onResponse Array<LifecycleHookRef> [] Hooks to run in the on_response phase
onError Array<LifecycleHookRef> [] Hooks to run in the on_error phase

OpenApiConfig

OpenAPI configuration

Field Type Default Description
enabled boolean false Enable OpenAPI generation (default: false for zero overhead)
title string "API" API title
version string "1.0.0" API version
description string \| null null API description (supports markdown)
swaggerUiPath string "/docs" Path to serve Swagger UI (default: "/docs")
redocPath string "/redoc" Path to serve Redoc (default: "/redoc")
openapiJsonPath string "/openapi.json" Path to serve OpenAPI JSON spec (default: "/openapi.json")
contact ContactInfo \| null null Contact information
license LicenseInfo \| null null License information
servers Array<ServerInfo> [] Server definitions
securitySchemes Record<string, SecuritySchemeInfo> {} Security schemes (auto-detected from middleware if not provided)

ParseRequest

Request body for POST /asyncapi/parse

Field Type Default Description
spec unknown Spec

ParseResult

Full parse result returned by POST /asyncapi/parse

Field Type Default Description
specVersion string Spec version
title string Title
apiVersion string Api version
channels Array<ParsedChannel> Channels
operations Array<ParsedOperation> Operations
messages Array<ParsedMessage> Messages

ParsedChannel

A single channel extracted from an AsyncAPI spec

Field Type Default Description
name string Channel key from the spec (e.g. "chat/messages")
address string Channel address / path
messages Array<string> Message names declared on this channel
bindings unknown \| null null Bindings (ws / http / amqp / …) as raw JSON for forward-compatibility

ParsedMessage

A resolved message (name + JSON Schema)

Field Type Default Description
name string Message name
schema unknown \| null null Resolved JSON Schema for the message payload, if available

ParsedOperation

A single operation extracted from an AsyncAPI spec

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

RateLimitConfig

Rate limiting configuration shared across runtimes

Field Type Default Description
perSecond number 100 Requests per second
burst number 200 Burst allowance
ipBased boolean 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 boolean 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 unknown \| null null Response body content
statusCode number 200 HTTP status code (defaults to 200)
headers Record<string, string> {} Response headers

ServerConfig

Server configuration

Field Type Default Description
host string "127.0.0.1" Host to bind to
port number 8000 Port to bind to
workers number 1 Number of Tokio runtime worker threads used by binding-managed server runtimes
enableRequestId boolean false Enable request ID generation and propagation
maxBodySize number \| null 10485760 Maximum request body size in bytes (None = unlimited, not recommended)
requestTimeout number \| null null Request timeout in seconds (None = no timeout)
compression CompressionConfig \| null null Enable compression middleware
rateLimit RateLimitConfig \| null null Enable rate limiting
jwtAuth JwtConfig \| null null JWT authentication configuration
apiKeyAuth ApiKeyConfig \| null null API Key authentication configuration
staticFiles Array<StaticFilesConfig> [] Static file serving configuration
gracefulShutdown boolean true Enable graceful shutdown on SIGTERM/SIGINT
shutdownTimeout number 30 Graceful shutdown timeout (seconds)
asyncapi AsyncApiConfig \| null null AsyncAPI HTTP endpoint configuration
openapi OpenApiConfig \| null null OpenAPI documentation configuration
jsonrpc JsonRpcConfig \| null null JSON-RPC configuration
grpc GrpcConfig \| null null gRPC configuration
backgroundTasks BackgroundTaskConfig Background task executor configuration
enableHttpTrace boolean false Enable per-request HTTP tracing (tower-http TraceLayer)

ServerInfo

Server information

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

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
graphqlAt()

Send a GraphQL query/mutation to a custom endpoint

Signature:

graphqlAt(endpoint: string, query: string, variables: unknown, operationName: string): Promise<ResponseSnapshot>

Example:

const result = await instance.graphqlAt("value", "value", {}, "value");

Parameters:

Name Type Required Description
endpoint string Yes The endpoint
query string Yes The query
variables unknown \| null No The variables
operationName string \| null No The operation name

Returns: ResponseSnapshot

Errors: Throws Error with a descriptive message.

graphql()

Send a GraphQL query/mutation

Signature:

graphql(query: string, variables: unknown, operationName: string): Promise<ResponseSnapshot>

Example:

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

Parameters:

Name Type Required Description
query string Yes The query
variables unknown \| null No The variables
operationName string \| null No The operation name

Returns: ResponseSnapshot

Errors: Throws Error with a descriptive message.

graphqlSubscriptionAt()

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:

graphqlSubscriptionAt(endpoint: string, query: string, variables: unknown, operationName: string): Promise<GraphQlSubscriptionSnapshot>

Example:

const result = await instance.graphqlSubscriptionAt("value", "value", {}, "value");

Parameters:

Name Type Required Description
endpoint string Yes The endpoint
query string Yes The query
variables unknown \| null No The variables
operationName string \| null No The operation name

Returns: GraphQlSubscriptionSnapshot

Errors: Throws Error with a descriptive message.

graphqlSubscription()

Send a GraphQL subscription (WebSocket).

Uses /graphql as the default subscription endpoint.

Signature:

graphqlSubscription(query: string, variables: unknown, operationName: string): Promise<GraphQlSubscriptionSnapshot>

Example:

const result = await instance.graphqlSubscription("value", {}, "value");

Parameters:

Name Type Required Description
query string Yes The query
variables unknown \| null No The variables
operationName string \| null No The operation name

Returns: GraphQlSubscriptionSnapshot

Errors: Throws Error with a descriptive message.


TestingSseEvent

A single Server-Sent Event.

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

ValidateRequest

Request body for POST /asyncapi/validate

Field Type Default Description
spec unknown Spec
channel string Channel
message string Message
payload unknown Payload

ValidationResponse

Response body for POST /asyncapi/validate

Field Type Default Description
valid boolean Valid
errors Array<string> 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
OnRequest On request
PreValidation Pre validation
PreHandler Pre handler
OnResponse On response
OnError On error

SecuritySchemeInfo

Security scheme types

Value Description
Http Http — Fields: scheme: string, bearerFormat: string
ApiKey Api key — Fields: location: string, name: string

Errors

AppError

Error type for application builder operations.

Errors are thrown as plain Error objects with descriptive messages.

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

Errors are thrown as plain Error objects with descriptive messages.

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

SchemaError

Error type for schema building operations

Errors are thrown as plain Error objects with descriptive messages.

Variant Description
BuildingFailed Generic schema building error
ValidationError Configuration validation error
ComplexityLimitExceeded Complexity limit exceeded
DepthLimitExceeded Depth limit exceeded

Edit this page on GitHub