Skip to main content

Import

import {
  createClient,
  handleErrors,
  sendRawRequest,
  buildRawRequestAction,
  inputs,
} from "@prismatic-io/spectral/dist/clients/http";

createClient

Signature

export const createClient = ({
  baseUrl,
  responseType,
  headers,
  timeout,
  params,
  debug,
  retryConfig,
}: ClientProps): HttpClient
Creates a reusable Axios instance (HttpClient) pre-configured with base URL, headers, retry logic, and optional debug logging. All standard Axios request methods (get, post, put, patch, delete, request, etc.) are available on the returned client.

ClientProps

baseUrl
string
The base URL prepended to every request (e.g. "https://api.acme.com/v2").
responseType
string
Expected response format. Passed directly to Axios. Common values: "json", "arraybuffer", "text", "document".
headers
Record<string, string>
Headers sent with every request. Typically used for Authorization or Content-Type.
params
Record<string, any>
URL search parameters added to every request.
timeout
number
Maximum time in milliseconds to wait for a response. Defaults to no timeout.
debug
boolean
default:"false"
When true, logs all request and response details (URL, headers, method, status) using context.logger. Large payloads (over 10 KB) and buffers are summarized by size.
retryConfig
RetryConfig
Retry configuration. See RetryConfig below.

Return value

export type HttpClient = AxiosInstance;
Returns an Axios instance with all standard Axios methods available.

RetryConfig

interface RetryConfig {
  retries?: number;
  retryDelay?: ((retryCount: number, error: AxiosError) => number) | number;
  retryAllErrors?: boolean;
  useExponentialBackoff?: boolean;
  retryCondition?: (error: AxiosError) => boolean;
  // ...plus all other IAxiosRetryConfig fields
}
retries
number
Number of retry attempts. Set to 0 to disable retries.
retryDelay
number | function
Fixed delay in milliseconds between retries, or a function (retryCount, error) => number. Ignored when useExponentialBackoff is true.
retryAllErrors
boolean
default:"false"
When true, retries on all error responses including 4xx. When false, retries only on 5xx and network errors (unless overridden by retryCondition).
useExponentialBackoff
boolean
default:"false"
When true, uses exponential backoff between retries (1×, 2×, 4×, 8× the base delay). If retryDelay is a number, that number is used as the base. Otherwise, uses axios-retry’s built-in exponential delay function.
retryCondition
(error: AxiosError) => boolean
Custom function to decide whether a specific error should trigger a retry. Overrides the default behavior when retryAllErrors is false.

Authentication helpers

toAuthorizationHeaders (internal)

The HTTP client module exports a private toAuthorizationHeaders helper used by buildRawRequestAction. It inspects a Connection and returns the correct Authorization header:
Connection typeHeader value
OAuth 2.0 (has token.access_token)Bearer <access_token>
API key (has fields.apiKey)Bearer <apiKey>
Basic auth (has fields.username + fields.password)Basic <base64(username:password)>
If none of the above match, it throws an error.

toFormData (internal)

Builds a multipart/form-data FormData object from key-value pairs. File data is converted to a Buffer via util.types.toBufferDataPayload.
const toFormData = (
  formData: KeyValuePair<unknown>[],
  fileData: KeyValuePair<unknown>[],
  fileDataFileNames?: Record<string, string>,
): FormData

handleErrors

Signature

export const handleErrors = (error: unknown): unknown
Inspects a thrown error. If it is an Axios error, returns a plain object with message, data, status, and headers. Otherwise returns the error unchanged. Use in a catch block to surface HTTP response details.
try {
  const response = await client.get("/resource");
} catch (rawError) {
  const error = handleErrors(rawError);
  // error.status, error.data, error.headers are available for Axios errors
  throw error;
}

sendRawRequest

Signature

export const sendRawRequest = async (
  baseUrl: string,
  values: SendRawRequestValues,
  authorizationHeaders?: Record<string, string>,
): Promise<AxiosResponse>
Builds and dispatches a single HTTP request from a structured input values object. Used internally by buildRawRequestAction. Throws when both data and form data inputs are specified simultaneously.

buildRawRequestAction

Signature

export const buildRawRequestAction = (
  baseUrl: string,
  label?: string,
  description?: string,
) => ActionDefinition
Generates a pre-built “Raw Request” action for a custom connector that exposes the full HTTP input set to integration builders. The action accepts a connection input plus the standard HTTP inputs.
import { buildRawRequestAction } from "@prismatic-io/spectral/dist/clients/http";

export const rawRequest = buildRawRequestAction(
  "https://api.acme.com/v2",
  "Raw Request",
  "Issue a raw HTTP request to the Acme API",
);

Pre-built inputs

The inputs export provides pre-built InputDefinition objects for all standard HTTP request fields. Import them when building custom HTTP actions:
import { inputs } from "@prismatic-io/spectral/dist/clients/http";
Input keyTypeRequiredDescription
urlstringYesRelative or absolute URL path
methodstringYesHTTP method (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, LINK, PURGE, UNLINK)
datastringNoRequest body payload
formDatakeyvaluelistNoForm fields for multipart form upload
fileDatakeyvaluelistNoFile fields for multipart form upload
fileDataFileNameskeyvaluelistNoFile names to apply to fileData keys
queryParamskeyvaluelistNoURL query parameters
headerskeyvaluelistNoRequest headers
responseTypestringYesExpected response type: json, text, arraybuffer, document. Default: json
timeoutstringNoRequest timeout in milliseconds
debugRequestbooleanNoLog request and response details
maxRetriesstringNoMaximum retry attempts. Default: 0
retryDelayMSstringNoDelay between retries in milliseconds. Default: 0
retryAllErrorsbooleanNoRetry on all errors, including 4xx. Default: false
useExponentialBackoffbooleanNoUse exponential backoff for retries. Default: false

Examples

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

const listRecords = action({
  display: { label: "List Records", description: "Fetches all records from Acme" },
  inputs: {
    connection: input({ label: "Connection", type: "connection" }),
    pageSize: input({ label: "Page Size", type: "string", default: "50" }),
  },
  perform: async (context, { connection, pageSize }) => {
    const client = createClient({
      baseUrl: "https://api.acme.com/v2",
      headers: {
        Authorization: `Bearer ${connection.token?.access_token}`,
        "Content-Type": "application/json",
      },
    });

    const { data } = await client.get("/records", {
      params: { page_size: pageSize },
    });

    return { data };
  },
});
  • util.types — type coercion helpers used throughout the HTTP client
  • createConnection — create test connection values for unit tests