@probitas/client-http

HTTP client for Probitas scenario testing framework.

This package provides an HTTP client designed for integration testing of HTTP APIs.

Features

  • All HTTP Methods: Support for GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
  • Request Building: Headers, query parameters, body (JSON, form, multipart)
  • Response Inspection: Status codes, headers, cookies, body parsing
  • Duration Tracking: Built-in timing for performance monitoring
  • Resource Management: Implements AsyncDisposable for proper cleanup

Installation

deno add jsr:@probitas/client-http

Quick Start

import { createHttpClient } from "@probitas/client-http";

interface User {
  id: string;
  name: string;
}

const http = createHttpClient({ url: "http://localhost:3000" });

// GET request
const res = await http.get("/users/123");
console.log("Status:", res.status);

// Extract typed data
const user = res.json as User;

// POST request
const created = await http.post("/users", {
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Jane" }),
});
console.log("Created:", created.status);

await http.close();

Using with using Statement

import { createHttpClient } from "@probitas/client-http";

await using http = createHttpClient({ url: "http://localhost:3000" });

const res = await http.get("/health");
console.log("Health:", res.ok);
PackageDescription
`@probitas/client`Core utilities and types
`@probitas/client-graphql`GraphQL client

Installation

deno add jsr:@probitas/client-http

Classes

class

#HttpError

class HttpError extends ClientError

HTTP error class for non-2xx responses.

This error is thrown (or returned in response.error) when the server responds with a 4xx or 5xx status code. It includes the response body for inspecting error details.

Examples

Check status code and body

import { createHttpClient, HttpError } from "@probitas/client-http";

const http = createHttpClient({ url: "http://localhost:3000", throwOnError: true });
try {
  await http.get("/not-found");
} catch (error) {
  if (error instanceof HttpError && error.status === 404) {
    console.log("Not found:", error.text);
  }
}
NameDescription
name
kind
statusHTTP status code
statusTextHTTP status text
headersResponse headers (null if not available)
body()Response body as raw bytes (null if no body)
arrayBuffer()Get body as ArrayBuffer (null if no body)
blob()Get body as Blob (null if no body)
text()Get body as text (null if no body)
json()Get body as parsed JSON (null if no body).
Constructor
new HttpError(status: number, statusText: string, options?: HttpErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"http"
  • readonlystatusnumber

    HTTP status code

  • readonlystatusTextstring

    HTTP status text

  • readonlyheadersHeaders | null

    Response headers (null if not available)

Methods
body(): unknown

Response body as raw bytes (null if no body)

arrayBuffer(): unknown

Get body as ArrayBuffer (null if no body)

blob(): unknown

Get body as Blob (null if no body)

text(): unknown

Get body as text (null if no body)

json(): unknown

Get body as parsed JSON (null if no body).

class

#HttpNetworkError

class HttpNetworkError extends ClientError

Error thrown when a network-level failure occurs.

This error indicates that the request could not be processed by the server due to network issues (connection refused, DNS resolution failure, etc.).

NameDescription
name
kind
Constructor
new HttpNetworkError(message: string, options?: ErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"network"

Interfaces

interface

#CookieConfig

interface CookieConfig

Cookie handling configuration.

NameDescription
disabledDisable automatic cookie handling.
initialInitial cookies to populate the cookie jar.
Properties
  • readonlydisabled?boolean

    Disable automatic cookie handling. When disabled, cookies are not stored or sent automatically.

  • readonlyinitial?Record<string, string>

    Initial cookies to populate the cookie jar.

interface

#HttpClient

interface HttpClient extends AsyncDisposable

HTTP client interface.

NameDescription
configClient configuration
get()Send GET request
head()Send HEAD request
post()Send POST request
put()Send PUT request
patch()Send PATCH request
delete()Send DELETE request
options()Send OPTIONS request
request()Send request with arbitrary method
getCookies()Get all cookies in the cookie jar.
setCookie()Set a cookie in the cookie jar.
clearCookies()Clear all cookies from the cookie jar.
close()Close the client and release resources
Properties
Methods
get(path: string, options?: HttpOptions): Promise<HttpResponse>

Send GET request

Parameters
head(path: string, options?: HttpOptions): Promise<HttpResponse>

Send HEAD request

Parameters
post(path: string, options?: HttpRequestOptions): Promise<HttpResponse>

Send POST request

Parameters
put(path: string, options?: HttpRequestOptions): Promise<HttpResponse>

Send PUT request

Parameters
patch(path: string, options?: HttpRequestOptions): Promise<HttpResponse>

Send PATCH request

Parameters
delete(path: string, options?: HttpRequestOptions): Promise<HttpResponse>

Send DELETE request

Parameters
options(path: string, options?: HttpOptions): Promise<HttpResponse>

Send OPTIONS request

Parameters
request(
  method: string,
  path: string,
  options?: HttpRequestOptions,
): Promise<HttpResponse>

Send request with arbitrary method

Parameters
getCookies(): Record<string, string>

Get all cookies in the cookie jar. Returns empty object if cookies are disabled.

setCookie(name: string, value: string): void

Set a cookie in the cookie jar.

Parameters
  • namestring
  • valuestring
clearCookies(): void

Clear all cookies from the cookie jar. No-op if cookies are disabled.

close(): Promise<void>

Close the client and release resources

interface

#HttpClientConfig

interface HttpClientConfig extends CommonOptions

HTTP client configuration.

NameDescription
urlBase URL for all requests.
headersDefault headers for all requests
fetchCustom fetch implementation (for testing/mocking)
redirectDefault redirect handling mode.
throwOnErrorWhether to throw HttpError for non-2xx responses.
cookiesCookie handling configuration.
Properties
  • readonlyurlstring | HttpConnectionConfig

    Base URL for all requests.

    Can be a URL string or a connection configuration object.

  • readonlyheaders?HeadersInit

    Default headers for all requests

  • readonlyfetch?fetch

    Custom fetch implementation (for testing/mocking)

  • readonlyredirect?RedirectMode

    Default redirect handling mode. Can be overridden per-request via HttpOptions.

  • readonlythrowOnError?boolean

    Whether to throw HttpError for non-2xx responses. Can be overridden per-request via HttpOptions.

  • readonlycookies?CookieConfig

    Cookie handling configuration. By default, the client maintains a cookie jar for automatic cookie management across requests. Set cookies: { disabled: true } to disable.

interface

#HttpConnectionConfig

interface HttpConnectionConfig extends CommonConnectionConfig

HTTP connection configuration.

Extends CommonConnectionConfig with HTTP-specific options.

NameDescription
protocolProtocol to use.
pathBase path prefix for all requests.
Properties
  • readonlyprotocol?"http" | "https"

    Protocol to use.

  • readonlypath?string

    Base path prefix for all requests.

interface

#HttpErrorOptions

interface HttpErrorOptions extends ErrorOptions

Options for creating an HttpError.

NameDescription
bodyResponse body as raw bytes
headersResponse headers
Properties
  • readonlybody?Uint8Array | null

    Response body as raw bytes

  • readonlyheaders?Headers | null

    Response headers

interface

#HttpOptions

interface HttpOptions extends CommonOptions

Options for individual HTTP requests.

NameDescription
queryQuery parameters (arrays for multi-value params)
headersAdditional request headers
redirectRedirect handling mode.
throwOnErrorWhether to throw HttpError for non-2xx responses.
Properties
  • readonlyquery?QueryParams

    Query parameters (arrays for multi-value params)

  • readonlyheaders?HeadersInit

    Additional request headers

  • readonlyredirect?RedirectMode

    Redirect handling mode.

  • readonlythrowOnError?boolean

    Whether to throw HttpError for non-2xx responses. When false, non-2xx responses are returned as HttpResponse.

interface

#HttpRequestOptions

interface HttpRequestOptions extends HttpOptions

Options for HTTP requests that may include a body.

NameDescription
bodyRequest body
Properties
interface

#HttpResponseError

interface HttpResponseError<T = any> extends HttpResponseBase<T>

HTTP response for error responses (4xx/5xx status codes).

Server received and processed the request, but returned an error status.

NameDescription
processedServer processed the request.
okResponse was not successful (4xx/5xx).
errorError describing the HTTP error.
statusHTTP status code (4xx/5xx).
statusTextHTTP status text.
headersResponse headers.
rawRaw Web standard Response.
Properties
  • readonlyprocessedtrue

    Server processed the request.

  • readonlyokfalse

    Response was not successful (4xx/5xx).

  • readonlyerrorHttpError

    Error describing the HTTP error.

  • readonlystatusnumber

    HTTP status code (4xx/5xx).

  • readonlystatusTextstring

    HTTP status text.

  • readonlyheadersHeaders

    Response headers.

  • readonlyrawglobalThis.Response

    Raw Web standard Response.

interface

#HttpResponseFailure

interface HttpResponseFailure<T = any> extends HttpResponseBase<T>

HTTP response for request failures (network errors, timeouts, etc.).

Request could not be processed by the server (network error, DNS failure, connection refused, timeout, aborted, etc.).

NameDescription
processedServer did not process the request.
okRequest failed.
errorError describing the failure (ConnectionError, TimeoutError, AbortError).
statusNo HTTP status (request didn't reach server).
statusTextNo HTTP status text (request didn't reach server).
headersNo headers (request didn't reach server).
bodyNo body (request didn't reach server).
rawNo raw response (request didn't reach server).
Properties
  • readonlyprocessedfalse

    Server did not process the request.

  • readonlyokfalse

    Request failed.

  • readonlyerrorHttpFailureError

    Error describing the failure (ConnectionError, TimeoutError, AbortError).

  • readonlystatusnull

    No HTTP status (request didn't reach server).

  • readonlystatusTextnull

    No HTTP status text (request didn't reach server).

  • readonlyheadersnull

    No headers (request didn't reach server).

  • readonlybodynull

    No body (request didn't reach server).

  • readonlyrawnull

    No raw response (request didn't reach server).

interface

#HttpResponseSuccess

interface HttpResponseSuccess<T = any> extends HttpResponseBase<T>

HTTP response for successful requests (2xx status codes).

Wraps Web standard Response, allowing body to be read synchronously and multiple times (unlike the streaming-based standard Response).

NameDescription
processedServer processed the request.
okResponse was successful (2xx).
errorNo error for successful responses.
statusHTTP status code (200-299).
statusTextHTTP status text.
headersResponse headers.
rawRaw Web standard Response.
Properties
  • readonlyprocessedtrue

    Server processed the request.

  • readonlyoktrue

    Response was successful (2xx).

  • readonlyerrornull

    No error for successful responses.

  • readonlystatusnumber

    HTTP status code (200-299).

  • readonlystatusTextstring

    HTTP status text.

  • readonlyheadersHeaders

    Response headers.

  • readonlyrawglobalThis.Response

    Raw Web standard Response.

Functions

function

#createHttpClient

function createHttpClient(config: HttpClientConfig): HttpClient

Create a new HTTP client instance.

The client provides methods for making HTTP requests with automatic cookie handling, response body pre-loading, and error handling.

Parameters
Returns

HttpClient — A new HTTP client instance

Examples

Basic usage with string URL

import { createHttpClient } from "@probitas/client-http";

const http = createHttpClient({ url: "http://localhost:3000" });

const response = await http.get("/users/123");
console.log(response.json);

await http.close();

With connection config object

import { createHttpClient } from "@probitas/client-http";

const http = createHttpClient({
  url: { host: "api.example.com", port: 443, protocol: "https" },
});
await http.close();

With default headers

import { createHttpClient } from "@probitas/client-http";

const http = createHttpClient({
  url: "http://localhost:3000",
  headers: {
    "Authorization": "Bearer token123",
    "Accept": "application/json",
  },
});
await http.close();

Using await using for automatic cleanup

import { createHttpClient } from "@probitas/client-http";

await using http = createHttpClient({ url: "http://localhost:3000" });
const response = await http.get("/health");
console.log(response.ok);

Types

type

#BodyInit

type BodyInit = string | Uint8Array | FormData | URLSearchParams | unknown

Request body type.

type

#HttpFailureError

type HttpFailureError = HttpNetworkError | AbortError | TimeoutError

Error types that indicate the operation was not processed. These are errors that occur before the request reaches the server.

type

#HttpResponse

type HttpResponse<T = any> = HttpResponseSuccess<T> | HttpResponseError<T> | HttpResponseFailure<T>

HTTP response union type representing all possible response states.

  • Success (2xx): processed: true, ok: true, error: null
  • Error (4xx/5xx): processed: true, ok: false, error: HttpError
  • Failure (network error): processed: false, ok: false, error: Error
type

#QueryParams

type QueryParams = URLSearchParams | Record<string, QueryValue | QueryValue[]>

Query parameters type - accepts URLSearchParams or plain object.

type

#QueryValue

type QueryValue = string | number | boolean

Query parameter value type.

type

#RedirectMode

type RedirectMode = "follow" | "manual" | "error"

Redirect handling mode.

  • "follow": Automatically follow redirects (default)
  • "manual": Return redirect response without following
  • "error": Throw error on redirect
Search Documentation