Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / APIs and data / API contractsRead Markdown
    On this page

    Call API contracts

    Call API contracts from imperative code or components with shared transport, caching, retry, and typed failure policies.

    For your own endpoint, first define its contract and route. For an external API, a standalone contract or generated OpenAPI client is enough; you do not need a Brix server route. Browser code imports the contract, never its implementation.

    Make a request

    #

    Start with executeApi in a browser event handler or another async operation. This example calls the profile endpoint from the server guide on the same origin:

    import { executeApi } from "#brix";
    import { updateProfileApiContract } from "#/features/profile/api/updateProfile/contract.ts";
    
    export async function saveDisplayName(profileId: string, displayName: string) {
      const result = await executeApi(updateProfileApiContract, {
        params: { profileId },
        body: { displayName },
      });
    
      if (result.isErr()) return "Could not save your profile.";
      return `Saved ${result.value.displayName}.`;
    }
    

    Calling saveDisplayName("profile-123", "Ada") sends a POST and returns a message you can display. The endpoint still needs a valid session and permission to update that profile. Network and HTTP failures become a typed Result, so handle them before reading .value. The component example below adds loading and error UI without managing that state yourself.

    Without baseUrl, Brix requests a root-relative URL such as /api/profiles/profile-123, which resolves against the page's origin in a browser but not in server code. For external APIs and calls from server code, supply an explicit baseUrl. When Node cannot parse the request URL, the call returns request-encoding after one attempt instead of a retryable network error, because every attempt would fail the same way. Use a configured client when several calls share an origin or transport settings; you do not need one for every contract.

    JSON calls send Accept: application/json, including bodyless and form-encoded requests; an explicit Accept header (matched case-insensitively, including configured-client defaults) wins. responseType: "text" or "stream" adds no default Accept. Content-Type describes the body being sent, so bodyless JSON requests omit it.

    Create a reusable API client

    #

    For a server client that uses request credentials, environment, or timings, define one brixServer.createService accessor at module scope in a server-only module. This is the canonical request-scoped client pattern; reuse the accessor from page loaders and route handlers.

    src/features/catalog/catalog-client.server.ts
    "use server";
    
    import { createApiClient } from "brix/contracts";
    import { brixServer } from "#brix/server";
    
    export const getCatalogClient = brixServer.createService((c) =>
      createApiClient({
        baseUrl: "https://catalog.example.com",
        timings: c.timings,
        dependency: "catalog",
        headers: async () => ({ Authorization: `Bearer ${await getAccessToken(c)}` }),
        timeout: 5_000,
        retry: { maxAttempts: 3, on: [429, 503], respectRetryAfter: true },
        redirect: "error",
      }),
    );
    

    Import getAccessToken from your application-owned credential provider; it must derive credentials from the trusted request context, not mutable global current-user state. The service itself does not authenticate requests: protect routes and enforce resource permissions explicitly.

    Inside a page loader or API handler, import the accessor and call it with that callback's c:

    Inside a page loader or API handler
    const result = await getCatalogClient(c).execute(getProductApiContract, {
      params: { productId: "123" },
      headers: { "X-Request-ID": c.get("brixRequestId") },
    });
    

    getProductApiContract is your catalogue's JSON GET contract. The call resolves to a typed Result: success contains the parsed product and failure contains an ApiRequestError.

    Repeated getCatalogClient(c) calls reuse the same client within that request; another request gets its own client. Do not define createService inside a loader/handler or recreate the configured client in each callback. Keep request contexts, tokens, and timings out of module-global client instances; lower-level connection pools may be shared. Services do not expose render, and page loaders need no context casts. For a complete loader example, see pages.

    client.execute returns ResultPromise<T, ApiRequestError> and preserves contract inference. Client defaults can include baseUrl, headers (an object or a sync or async function), timeout, retry, cache, redirect, Fetch credentials, validateResponse, onFetch, timings, and dependency. Per-call values override defaults; headers merge case-insensitively with call headers winning. Omitted credentials preserve Fetch's same-origin default.

    For JSON contracts with a response schema, parsing is mandatory: transforms and defaults define the returned type. validateResponse: false is rejected by TypeScript and returns request-encoding before fetch for JavaScript callers. A client configured with that default can still call schema-less contracts; schema-backed calls and hooks must override it with validateResponse: true. Let the client type infer its defaults. Explicit responseType: "text" or "stream" remains available for raw responses and returns string or Response, never the schema's parsed output.

    An async header resolver runs once per execution before retries, even for a cache hit. Its failure becomes an ApiRequestError, not a rejected promise. Timeout covers credential resolution and HTTP work. Use request-scoped server clients for user credentials rather than mutable global current-user state.

    Use plain executeApi(contract, options) for one-off calls. Both forms are uncached by default and work anywhere with standard Fetch.

    Query options use schema input values and are required when the query object has required keys. Direct route execution normalizes JSON bodies and query values through the HTTP wire representation, including Date JSON strings and string-form booleans.

    Direct route.execute(c, options) returns Promise<T> and rejects on validation or handler errors; use try/catch. It does not return the Result used by executeApi, configured clients, or hooks.

    Paths with only optional parameters allow calls without params; wildcard paths require params: { "*": "path/to/file" }. Required query input cannot be bypassed by omitting the options argument. HTTP 204 responses parse undefined through the response schema, including its transforms, consistently with direct execution and the test harness.

    On a Brix server, pass c.timings and a stable dependency label as above. Every native attempt is measured through response-body consumption, including failed attempts. Cache and memory hits exclude upstream HTTP work; remote cache operations are measured separately as cache.dynamodb (including S3 overflow) or cache.fastly. Retry backoff, request/response schema validation, and other application CPU work are excluded. On a shared cache flight, the initiator owns upstream and cache-write spans; joiners retain only their own cache-read spans. A streaming request ends its measurement when response headers arrive; later body-stream consumption is not included. Do not wrap application methods in another measurement or attach one request's c.timings to a shared client. Keep the client request-scoped and reuse lower-level connection pools instead.

    For a contract declaring bodyEncoding: "form-urlencoded", pass the same typed object to executeApi, client.execute, or useApi. The contract selects serialization and the UTF-8 form content type; there is no per-call encoder. A compatible content-type header is accepted and normalized; a conflicting one fails before fetch. See form input rules.

    Invalid outgoing wire values or serialization failures return ApiRequestError with kind: "request-encoding", status: 0, and data: null, without fetching or retrying. These diagnostics omit body values and the original serialization exception. This is wire validation, not outbound schema parsing: request transforms/defaults do not execute before sending.

    OAuth token exchanges belong in server-only modules. Keep credentials and token storage out of shared contracts and browser bundles, avoid logging complete errors or token responses, and do not enable retryNonIdempotent for single-use authorization codes. A timeout does not prove that a code was not consumed. HTTP and response-validation errors may retain sensitive response data; Brix does not automatically redact it.

    Callers sharing a cache-first origin load receive separate ApiRequestError objects and separate Brix-parsed JSON error bodies. Diagnostic cause, the internal raw response, and custom application-supplied error data retain their references; treat them as read-only. Brix does not deep-clone arbitrary errors or transport objects.

    Bound a call with one deadline

    #

    timeout is an integer number of milliseconds from 0 through 2,147,483,647. Omit it for no Brix deadline; 0 schedules an immediate timeout using AbortSignal.timeout(0), not an unlimited wait. An explicit per-call timeout: undefined clears a configured client's timeout default. Invalid values produce a nonretryable request-encoding Result with status 0 before credentials or HTTP work.

    The deadline spans credential resolution, cache waiting, HTTP body reads, retries, and retry delays; it does not reset per attempt. Expiry returns timeout with status 408 and does not retry or serve stale data. An independent transport timeout before that deadline can still qualify for retry or stale fallback. Caller cancellation remains aborted. Synchronous work cannot be preempted, and cancellation cannot stop arbitrary work inside a credential resolver.

    With responseType: "stream", Brix returns the successful Response without consuming its body. Later body-read failures belong to the caller and are not retried; the Fetch signal can still abort the stream after Brix returns.

    Consume from a component

    #

    In a server-rendered application, put interactive code in an island. This example uses the profile contract from the server guide and displays request failure without exposing a provider's response body:

    src/features/profile/ProfileForm.tsx
    "use island";
    
    import { useApi } from "brix/hooks";
    import { updateProfileApiContract } from "#/features/profile/api/updateProfile/contract.ts";
    
    export function ProfileForm() {
      const profileApi = useApi(updateProfileApiContract);
    
      const save = () =>
        profileApi.execute({
          params: { profileId: "profile-123" },
          body: { displayName: "Ada" },
        });
    
      return (
        <>
          <button type="button" disabled={profileApi.isFetching.value} onClick={save}>
            {profileApi.isFetching.value ? "Saving…" : "Save"}
          </button>
          {profileApi.isError.value && <p role="alert">Could not save. Please try again.</p>}
          {profileApi.isSuccess.value && <p>Saved.</p>}
        </>
      );
    }
    

    useApi forwards the same credentials option. Exceptions or rejected promises from onSuccess and onError are logged without replacing the execution Result or changing hook state.

    The hook exposes data, error, status, isLoading, isFetching, isSuccess, isError, execute, and reset. Mounting does not fetch. isLoading means a first load with no data; isFetching includes background refreshes. Existing data remains visible during refetch.

    execute captures the contract and options from its render, including callbacks. Suspended React renders cannot change requests made by the committed UI. Its identity (and the result object's identity) changes when the contract or options object changes; inline options create a new callback each render. Keep dependencies current, and memoize options if an effect depends on execute to avoid repeated requests. A retained older callback, in-flight request, or cache invalidation refresh keeps its original configuration; explicitly execute the current callback to adopt new options.

    Every execution returns its own Result. Supersession, reset, and unmount fence stale signal and callback updates. They abort non-cacheable prior work; shared cacheable work continues until its last caller detaches.

    In React applications, hiding a component with React Activity also releases the request and cache observation, while retaining data and completed errors. Interrupted loading settles to idle without data or success with retained data; isFetching and isLoading become false. Revealing does not fetch or reconnect observation. Call execute() explicitly to resume: until then, retained data may be stale and cache writes or invalidations do not update this hook. Cancellation does not invoke its callbacks.

    Pass a configured client to share transport defaults:

    const productApi = useApi(getProductApiContract, {
      client: catalogClient,
      initialData: serverProduct,
    });
    

    initialData starts local state as successful but does not populate shared storage. Preact applications import from brix/hooks; React applications use the matching binding described in React.

    Opt into native GET caching

    #

    Share a cache instance, but choose the policy on each request or hook query. This keeps the lifetime and sharing scope beside the read they apply to.

    Create the cache and client in a browser-safe module, outside rendering:

    src/features/catalog/catalog-client.ts
    import { createDataCache } from "brix/cache";
    import { createApiClient } from "brix/contracts";
    
    export const dataCache = createDataCache();
    export const catalogClient = createApiClient({
      baseUrl: "https://catalog.example.com",
    });
    

    In an async operation, opt this read into caching:

    const product = await catalogClient.execute(getProductApiContract, {
      params: { productId: "123" },
      cache: dataCache.public("30s"),
    });
    

    Inside a component, give the hook the same request policy and call execute from an event handler:

    Inside a catalogue island component
    const productApi = useApi(getProductApiContract, {
      client: catalogClient,
      cache: dataCache.public("30s"),
    });
    
    return (
      <button onClick={() => productApi.execute({ params: { productId: "123" } })}>Load product</button>
    );
    

    The hook can reuse the imperative read because both use the same cache and policy for an identical request. Client-level cache defaults are also supported, but use them only when the client's reads intentionally share a strategy. Only validated JSON GETs participate. Mutations, text or streams, schema-less calls with disabled response validation, and cache: false bypass caching.

    Public policy permits sharing. Private reads require an explicit nonsecret partition:

    cache: dataCache.private(session.cacheScope, "30s");
    

    Partitioning is not authorization. Rotate the scope on login or permission change and invalidate/reset on logout. Cookie-only identity is not visible to Brix. See caching for TTL, stale fallback, DynamoDB, response vetoes, and security boundaries.

    Mutations never invalidate reads automatically:

    For progressive forms that return expected validation errors as data, check the saved discriminator before invalidating. A successful HTTP request is not necessarily a saved mutation. The example below assumes every successful response represents a completed write.

    await updateProfileApi.execute({ params: { profileId }, body }).unwrap();
    await dataCache.invalidate(getProfileApiContract);
    

    Awaiting invalidation confirms storage removal. Active hooks refresh in the background; refresh failure updates hook state but does not reject successful invalidation.

    Configure retries deliberately

    #
    const result = executeApi(getProductApiContract, {
      params: { productId: "123" },
      retry: {
        maxAttempts: 3,
        on: [429, 500, 502, 503, 504],
        respectRetryAfter: true,
      },
    });
    

    maxAttempts includes the initial request. Delays use full jitter with a 1,000 ms base and 10,000 ms cap by default. maxAttempts must be a positive integer, baseDelay and maxDelay non-negative integer milliseconds, and on an array of integer status codes. Other values, such as Infinity attempts or a NaN delay read from an unset environment variable, return request-encoding without fetching, rather than retrying forever or without backoff.

    With respectRetryAfter: true, Retry-After replaces jitter with non-negative integer seconds or the time remaining until a canonical IMF-fixdate, measured against the client clock. For example, Wed, 14 Oct 2026 12:00:03 GMT uses the required HTTP sender format. Zero and past dates retry without a backoff wait. Brix supports only this date format, not obsolete RFC 850 or asctime dates; it does not implement legacy year interpretation. Calendar dates must round-trip exactly, including the weekday; leap-second notation is unsupported. Invalid, unsupported, or nonfinite values fall back to jitter; signed, fractional, and exponent-form seconds are invalid. Only when Retry-After is absent, Contentful's X-Contentful-RateLimit-Reset supplies positive finite numeric seconds, including fractions; zero still falls back to jitter for that provider header. Cancellation interrupts either wait.

    maxDelay caps header delays as well as exponential backoff. A valid header delay greater than maxDelay (10,000 ms by default) stops automatic retries and returns the last HTTP error (subject to configured cache stale fallback), so a server cannot stall the caller for hours and Brix never retries before the server allows it. Raise maxDelay when longer server-directed waits are acceptable, and set timeout when the whole call needs a deadline. See RFC 9110 §10.2.3.

    GET, PUT, and DELETE retry network errors and timeouts. POST and PATCH do not unless retryNonIdempotent: true; enable that only when an idempotency key or endpoint semantics make duplicate execution safe. Cache stale fallback is considered only after retries finish.

    Interrupted successful response bodies are transport failures, including in text mode, and follow the same retry and stale-fallback eligibility as a failed Fetch. Malformed JSON in a completely read body is decode: it is never retried or hidden by stale fallback. Non-success responses retain their HTTP status even when their error body cannot be read.

    Retries remain opt-in, and the headers do not change eligible methods or status codes.

    Handle request failures

    #
    const result = await catalogClient.execute(getProductApiContract, {
      params: { productId: "123" },
    });
    
    if (result.isErr()) {
      result.error.kind;
      result.error.status;
      result.error.data;
      result.error.hasStatus(404);
    }
    

    Error kinds are request-encoding, http, network, timeout, aborted, decode, and response-validation. error.path is the concrete request pathname, such as /items/7, or the contract template when the URL could not be built. A response schema whose transform throws, or that uses an async refinement, returns response-validation with the thrown error as cause; Brix parses response schemas synchronously. Treat them as expected typed outcomes; use .unwrap() only where converting an error into a panic is intentional. See results.

    Cross-origin browser clients need an explicit base URL, a matching server CORS allowlist, and, for mutations, the client origin in csrf.trustedOrigins; see cross-origin browser calls. Set redirect: "error" for server calls where redirects could cross a trust boundary. Test handlers through the route harness and external calls with contract mocks; see testing.