# @probitas/client-http > Version: 0.7.2 HTTP client for [Probitas](https://github.com/probitas-test/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 ```bash deno add jsr:@probitas/client-http ``` ## Quick Start ```ts 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 ```ts 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); ``` ## Related Packages | Package | Description | |---------|-------------| | [`@probitas/client`](https://jsr.io/@probitas/client) | Core utilities and types | | [`@probitas/client-graphql`](https://jsr.io/@probitas/client-graphql) | GraphQL client | ## Links - [GitHub Repository](https://github.com/probitas-test/probitas-client) - [Probitas Framework](https://github.com/probitas-test/probitas) ## Classes ### `HttpError` ```typescript 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. **Constructor:** ```typescript new HttpError(status: number, statusText: string, options?: HttpErrorOptions) ``` **Properties:** - [readonly] `name`: `string` - [readonly] `kind`: `"http"` - [readonly] `status`: `number` — HTTP status code - [readonly] `statusText`: `string` — HTTP status text - [readonly] `headers`: `Headers | null` — Response headers (null if not available) **Methods:** ```typescript body(): unknown ``` Response body as raw bytes (null if no body) ```typescript arrayBuffer(): unknown ``` Get body as ArrayBuffer (null if no body) ```typescript blob(): unknown ``` Get body as Blob (null if no body) ```typescript text(): unknown ``` Get body as text (null if no body) ```typescript json(): unknown ``` Get body as parsed JSON (null if no body). **Example:** Check status code and body ```ts 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); } } ``` --- ### `HttpNetworkError` ```typescript 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.). **Constructor:** ```typescript new HttpNetworkError(message: string, options?: ErrorOptions) ``` **Properties:** - [readonly] `name`: `string` - [readonly] `kind`: `"network"` --- ## Interfaces ### `HttpResponseError` ```typescript interface HttpResponseError extends HttpResponseBase ``` HTTP response for error responses (4xx/5xx status codes). Server received and processed the request, but returned an error status. **Properties:** - [readonly] `processed`: `true` — Server processed the request. - [readonly] `ok`: `false` — Response was not successful (4xx/5xx). - [readonly] `error`: `HttpError` — Error describing the HTTP error. - [readonly] `status`: `number` — HTTP status code (4xx/5xx). - [readonly] `statusText`: `string` — HTTP status text. - [readonly] `headers`: `Headers` — Response headers. - [readonly] `raw`: `globalThis.Response` — Raw Web standard Response. --- ### `HttpResponseFailure` ```typescript interface HttpResponseFailure extends HttpResponseBase ``` 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.). **Properties:** - [readonly] `processed`: `false` — Server did not process the request. - [readonly] `ok`: `false` — Request failed. - [readonly] `error`: `HttpFailureError` — Error describing the failure (ConnectionError, TimeoutError, AbortError). - [readonly] `status`: `null` — No HTTP status (request didn't reach server). - [readonly] `statusText`: `null` — No HTTP status text (request didn't reach server). - [readonly] `headers`: `null` — No headers (request didn't reach server). - [readonly] `body`: `null` — No body (request didn't reach server). - [readonly] `raw`: `null` — No raw response (request didn't reach server). --- ### `HttpResponseSuccess` ```typescript interface HttpResponseSuccess extends HttpResponseBase ``` 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). **Properties:** - [readonly] `processed`: `true` — Server processed the request. - [readonly] `ok`: `true` — Response was successful (2xx). - [readonly] `error`: `null` — No error for successful responses. - [readonly] `status`: `number` — HTTP status code (200-299). - [readonly] `statusText`: `string` — HTTP status text. - [readonly] `headers`: `Headers` — Response headers. - [readonly] `raw`: `globalThis.Response` — Raw Web standard Response. --- ### `HttpOptions` ```typescript interface HttpOptions extends CommonOptions ``` Options for individual HTTP requests. **Properties:** - [readonly] `query?`: `QueryParams` — Query parameters (arrays for multi-value params) - [readonly] `headers?`: `HeadersInit` — Additional request headers - [readonly] `redirect?`: `RedirectMode` — Redirect handling mode. - [readonly] `throwOnError?`: `boolean` — Whether to throw HttpError for non-2xx responses. When false, non-2xx responses are returned as HttpResponse. --- ### `HttpRequestOptions` ```typescript interface HttpRequestOptions extends HttpOptions ``` Options for HTTP requests that may include a body. **Properties:** - [readonly] `body?`: `BodyInit` — Request body --- ### `CookieConfig` ```typescript interface CookieConfig ``` Cookie handling configuration. **Properties:** - [readonly] `disabled?`: `boolean` — Disable automatic cookie handling. When disabled, cookies are not stored or sent automatically. - [readonly] `initial?`: `Record` — Initial cookies to populate the cookie jar. --- ### `HttpConnectionConfig` ```typescript interface HttpConnectionConfig extends CommonConnectionConfig ``` HTTP connection configuration. Extends CommonConnectionConfig with HTTP-specific options. **Properties:** - [readonly] `protocol?`: `"http" | "https"` — Protocol to use. - [readonly] `path?`: `string` — Base path prefix for all requests. --- ### `HttpClientConfig` ```typescript interface HttpClientConfig extends CommonOptions ``` HTTP client configuration. **Properties:** - [readonly] `url`: `string | HttpConnectionConfig` — Base URL for all requests. Can be a URL string or a connection configuration object. - [readonly] `headers?`: `HeadersInit` — Default headers for all requests - [readonly] `fetch?`: `fetch` — Custom fetch implementation (for testing/mocking) - [readonly] `redirect?`: `RedirectMode` — Default redirect handling mode. Can be overridden per-request via HttpOptions. - [readonly] `throwOnError?`: `boolean` — Whether to throw HttpError for non-2xx responses. Can be overridden per-request via HttpOptions. - [readonly] `cookies?`: `CookieConfig` — Cookie handling configuration. By default, the client maintains a cookie jar for automatic cookie management across requests. Set `cookies: { disabled: true }` to disable. --- ### `HttpClient` ```typescript interface HttpClient extends AsyncDisposable ``` HTTP client interface. **Properties:** - [readonly] `config`: `HttpClientConfig` — Client configuration **Methods:** ```typescript get(path: string, options?: HttpOptions): Promise ``` Send GET request ```typescript head(path: string, options?: HttpOptions): Promise ``` Send HEAD request ```typescript post(path: string, options?: HttpRequestOptions): Promise ``` Send POST request ```typescript put(path: string, options?: HttpRequestOptions): Promise ``` Send PUT request ```typescript patch(path: string, options?: HttpRequestOptions): Promise ``` Send PATCH request ```typescript delete(path: string, options?: HttpRequestOptions): Promise ``` Send DELETE request ```typescript options(path: string, options?: HttpOptions): Promise ``` Send OPTIONS request ```typescript request( method: string, path: string, options?: HttpRequestOptions, ): Promise ``` Send request with arbitrary method ```typescript getCookies(): Record ``` Get all cookies in the cookie jar. Returns empty object if cookies are disabled. ```typescript setCookie(name: string, value: string): void ``` Set a cookie in the cookie jar. ```typescript clearCookies(): void ``` Clear all cookies from the cookie jar. No-op if cookies are disabled. ```typescript close(): Promise ``` Close the client and release resources --- ### `HttpErrorOptions` ```typescript interface HttpErrorOptions extends ErrorOptions ``` Options for creating an HttpError. **Properties:** - [readonly] `body?`: `Uint8Array | null` — Response body as raw bytes - [readonly] `headers?`: `Headers | null` — Response headers --- ## Functions ### `createHttpClient` ```typescript 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:** - `config`: `HttpClientConfig` — - Client configuration including URL and default options **Returns:** `HttpClient` A new HTTP client instance **Example:** Basic usage with string URL ```ts 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 ```ts import { createHttpClient } from "@probitas/client-http"; const http = createHttpClient({ url: { host: "api.example.com", port: 443, protocol: "https" }, }); await http.close(); ``` With default headers ```ts 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 ```ts 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 ### `HttpResponse` ```typescript type HttpResponse = HttpResponseSuccess | HttpResponseError | HttpResponseFailure ``` 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` --- ### `QueryValue` ```typescript type QueryValue = string | number | boolean ``` Query parameter value type. --- ### `BodyInit` ```typescript type BodyInit = string | Uint8Array | FormData | URLSearchParams | unknown ``` Request body type. --- ### `RedirectMode` ```typescript type RedirectMode = "follow" | "manual" | "error" ``` Redirect handling mode. - "follow": Automatically follow redirects (default) - "manual": Return redirect response without following - "error": Throw error on redirect --- ### `QueryParams` ```typescript type QueryParams = URLSearchParams | Record ``` Query parameters type - accepts URLSearchParams or plain object. --- ### `HttpFailureError` ```typescript 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. --- ## Related Links ### This Package - [`BodyInit`](https://probitas-test.github.io/documents/api/client-http#BodyInit) - [`CookieConfig`](https://probitas-test.github.io/documents/api/client-http#CookieConfig) - [`HttpClient`](https://probitas-test.github.io/documents/api/client-http#HttpClient) - [`HttpClientConfig`](https://probitas-test.github.io/documents/api/client-http#HttpClientConfig) - [`HttpConnectionConfig`](https://probitas-test.github.io/documents/api/client-http#HttpConnectionConfig) - [`HttpError`](https://probitas-test.github.io/documents/api/client-http#HttpError) - [`HttpErrorOptions`](https://probitas-test.github.io/documents/api/client-http#HttpErrorOptions) - [`HttpFailureError`](https://probitas-test.github.io/documents/api/client-http#HttpFailureError) - [`HttpNetworkError`](https://probitas-test.github.io/documents/api/client-http#HttpNetworkError) - [`HttpOptions`](https://probitas-test.github.io/documents/api/client-http#HttpOptions) - [`HttpRequestOptions`](https://probitas-test.github.io/documents/api/client-http#HttpRequestOptions) - [`HttpResponse`](https://probitas-test.github.io/documents/api/client-http#HttpResponse) - [`HttpResponseError`](https://probitas-test.github.io/documents/api/client-http#HttpResponseError) - [`HttpResponseFailure`](https://probitas-test.github.io/documents/api/client-http#HttpResponseFailure) - [`HttpResponseSuccess`](https://probitas-test.github.io/documents/api/client-http#HttpResponseSuccess) - [`QueryParams`](https://probitas-test.github.io/documents/api/client-http#QueryParams) - [`QueryValue`](https://probitas-test.github.io/documents/api/client-http#QueryValue) - [`RedirectMode`](https://probitas-test.github.io/documents/api/client-http#RedirectMode) ### Other Packages - [`AbortError`](https://probitas-test.github.io/documents/api/client#AbortError) (@probitas/client) - [`CommonConnectionConfig`](https://probitas-test.github.io/documents/api/client#CommonConnectionConfig) (@probitas/client) - [`CommonOptions`](https://probitas-test.github.io/documents/api/client#CommonOptions) (@probitas/client) - [`TimeoutError`](https://probitas-test.github.io/documents/api/client#TimeoutError) (@probitas/client) ### Built-in Types - [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) - [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type) - [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) --- *Last updated: 2026-01-12*