Skip to main content
The Spectral HTTP client is built on top of Axios and provides helpers for creating authenticated clients, handling retries, uploading files, and building generic raw request actions. Import from @prismatic-io/spectral/dist/clients/http:
import {
  createClient,
  handleErrors,
  sendRawRequest,
  buildRawRequestAction,
  toAuthorizationHeaders,
  inputs,
} from "@prismatic-io/spectral/dist/clients/http";
import { exponentialDelay, isNetworkOrIdempotentRequestError } from "@prismatic-io/spectral/dist/clients/http";

createClient

Creates a reusable Axios HTTP client instance configured with a base URL, default headers, timeout, and optional retry logic.
export const createClient = ({
  baseUrl,
  responseType,
  headers,
  timeout,
  params,
  debug,
  retryConfig,
}: ClientProps): HttpClient
baseUrl
string
The API’s base URL (e.g. https://api.acme.com/v2/). All relative request URLs are resolved against this.
responseType
string
The type of response to expect. Set to 'json' to automatically parse a JSON response, or 'arraybuffer' for binary data. Passed directly to Axios.
headers
object
Headers to send with every request (e.g. an Authorization header).
params
object
URL search parameters appended to every request.
timeout
number
The maximum time in milliseconds to wait for a response. Defaults to no timeout.
debug
boolean
When true, logs every request and response to the console. Useful during development.
retryConfig
RetryConfig
Configuration that controls if and how failed requests are retried. See RetryConfig below.

Basic usage

import { createClient } from "@prismatic-io/spectral/dist/clients/http";

const client = createClient({
  baseUrl: "https://api.acme.com/v2/",
  headers: { Authorization: "Bearer my-token" },
});

const { data } = await client.get("/users");

HttpClient type

HttpClient is a type alias for an Axios instance:
export type HttpClient = AxiosInstance;
Once you have a client, you can use the full Axios API — .get(), .post(), .put(), .patch(), .delete(), .request(), and so on.

RetryConfig

Pass a retryConfig object to createClient to automatically retry failed requests.
interface RetryConfig {
  /** Number of retry attempts. */
  retries?: number;
  /** Milliseconds to wait between retries, or a function (retryCount, error) => number. */
  retryDelay?: number | ((retryCount: number, error: Error) => number);
  /** When true, retry on all errors. When false, only retry on network errors and idempotent HTTP 5xx responses. */
  retryAllErrors?: boolean;
  /** When true, double the retryDelay after each attempt. If retryDelay is omitted, uses axios-retry's exponentialDelay. */
  useExponentialBackoff?: boolean;
  /** Custom function to decide whether to retry. Takes precedence over retryAllErrors when retryAllErrors is false. */
  retryCondition?: (error: Error) => boolean;
}
const client = createClient({
  baseUrl: "https://api.acme.com/v2/",
  retryConfig: {
    retries: 3,
    retryDelay: 500, // wait 500 ms between each retry
  },
});

exponentialDelay and isNetworkOrIdempotentRequestError

These are re-exported from axios-retry for convenience.
  • exponentialDelay — A pre-built delay function that doubles the wait after each retry attempt.
  • isNetworkOrIdempotentRequestError — The default retry condition. Returns true for network errors and idempotent HTTP methods with 5xx responses.
import {
  exponentialDelay,
  isNetworkOrIdempotentRequestError,
} from "@prismatic-io/spectral/dist/clients/http";

const client = createClient({
  baseUrl: "https://api.acme.com/v2/",
  retryConfig: {
    retries: 3,
    retryDelay: exponentialDelay,
    retryCondition: (error) =>
      isNetworkOrIdempotentRequestError(error) || error.response?.status === 429,
  },
});

Authorization helpers

toAuthorizationHeaders

Inspects a Spectral Connection object and returns an Authorization header automatically. The detection order is:
  1. OAuth access token — if connection.token.access_token is set, returns { Authorization: "Bearer <token>" }.
  2. API key — if connection.fields.apiKey is set, returns { Authorization: "Bearer <apiKey>" }.
  3. Username / password — if both connection.fields.username and connection.fields.password are set, returns { Authorization: "Basic <base64(user:pass)>" }.
  4. Error — throws if none of the above are present.
const headers = toAuthorizationHeaders(connection);
// e.g. { Authorization: "Bearer eyJ..." }
// connection.token.access_token = "eyJ..."
const headers = toAuthorizationHeaders(connection);
// => { Authorization: "Bearer eyJ..." }

const client = createClient({
  baseUrl: "https://api.acme.com/",
  headers,
});

Form data and file uploads

The HTTP client supports multipart form uploads through the sendRawRequest function and the built-in inputs. For direct use, construct a FormData instance and pass it as the request body. The client automatically sets the correct Content-Type: multipart/form-data boundary headers.
import FormData from "form-data";

const form = new FormData();
form.append("name", "Alice");
form.append("avatar", fileBuffer, { filename: "avatar.png" });

const { data } = await client.post("/upload", form, {
  headers: form.getHeaders(),
});
The built-in sendRawRequest function calls an internal toFormData helper that converts a list of {key, value} pairs into a FormData object and uses util.types.toBufferDataPayload to handle file data.

handleErrors

A global error handler that enriches Axios errors with structured response details.
export const handleErrors = (error: unknown): unknown
When the error is an Axios error, returns an object with:
  • message — the error message string
  • data — the response body
  • status — the HTTP status code
  • headers — the response headers
For non-Axios errors, the original error is returned unchanged.
try {
  const { data } = await client.get("/users");
  return { data };
} catch (error) {
  throw handleErrors(error);
}

sendRawRequest

Executes a fully configured HTTP request from a set of input values. Used internally by buildRawRequestAction to power raw request actions.
export const sendRawRequest = async (
  baseUrl: string,
  values: SendRawRequestValues,
  authorizationHeaders: Record<string, string> = {},
): Promise<AxiosResponse>

buildRawRequestAction

Generates a ready-to-use Spectral action that exposes all HTTP request inputs (method, URL, headers, query params, body, form data, file data, timeouts, retries, and response type) and performs the request against a fixed base URL.
export const buildRawRequestAction = (
  baseUrl: string,
  label = "Raw Request",
  description = "Issue a raw HTTP request",
) => action
import { buildRawRequestAction } from "@prismatic-io/spectral/dist/clients/http";

export const rawRequest = buildRawRequestAction("https://api.acme.com/v2");
buildRawRequestAction automatically wires the connection input to toAuthorizationHeaders, so end users do not need to manage authorization headers manually.

Built-in inputs

The inputs export from the HTTP client package is a map of pre-configured Spectral inputs. You can spread them directly into an action’s inputs object.
import { inputs } from "@prismatic-io/spectral/dist/clients/http";

export const myAction = action({
  display: { label: "My Action", description: "..." },
  inputs: { connection: { label: "Connection", type: "connection", required: true }, ...inputs },
  perform: async (context, params) => { /* ... */ },
});
The available inputs are:
The URL path to call (e.g. /sobjects/Account). Combined with the client’s baseUrl.
The HTTP method. One of DELETE, GET, HEAD, LINK, OPTIONS, PATCH, POST, PURGE, PUT, UNLINK.
The HTTP body payload to send (e.g. {"exampleKey": "Example Data"}).
A key-value list of fields to send as a multipart form upload.
A key-value list of file contents to send as a multipart form upload. Keys are used as field names.
Overrides the file name for each fileData key. Keys must match fileData keys.
Additional headers to send with the request (e.g. User-Agent: curl/7.64.1).
Query parameters appended to the URL (e.g. ?key1=value1&key2=value2).
The expected response format: arraybuffer, document, json, or text.
The maximum time in milliseconds the client will wait for a response.
The maximum number of retry attempts. Set to 0 to disable retries.
Milliseconds to wait between retries. Only used when useExponentialBackoff is false.
When true, retries on all error responses including HTTP 429 and other 4xx codes. When false, only retries on 5xx and network errors.
When true, enables exponential backoff between retry attempts. retryDelayMS is ignored when this is enabled.
When true, logs the current request and response to the console.