@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
AsyncDisposablefor 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);
Related Packages
| Package | Description |
|---|---|
| `@probitas/client` | Core utilities and types |
| `@probitas/client-graphql` | GraphQL client |
Links
Installation
deno add jsr:@probitas/client-httpClasses
#HttpError
class HttpError extends ClientErrorClientErrorHTTP 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);
}
}
| Name | Description |
|---|---|
name | — |
kind | — |
status | HTTP status code |
statusText | HTTP status text |
headers | Response 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
- readonly
namestring - readonly
kind"http" - readonly
statusnumberHTTP status code
- readonly
statusTextstringHTTP status text
- readonly
headersHeaders | nullResponse headers (null if not available)
Methods
body(): unknownResponse body as raw bytes (null if no body)
arrayBuffer(): unknownGet body as ArrayBuffer (null if no body)
blob(): unknownGet body as Blob (null if no body)
text(): unknownGet body as text (null if no body)
json(): unknownGet body as parsed JSON (null if no body).
#HttpNetworkError
class HttpNetworkError extends ClientErrorClientErrorError 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
new HttpNetworkError(message: string, options?: ErrorOptions)Properties
- readonly
namestring - readonly
kind"network"
Interfaces
#CookieConfig
interface CookieConfigCookie handling configuration.
| Name | Description |
|---|---|
disabled | Disable automatic cookie handling. |
initial | Initial cookies to populate the cookie jar. |
Properties
- readonly
disabled?booleanDisable automatic cookie handling. When disabled, cookies are not stored or sent automatically.
- readonly
initial?Record<string, string>Initial cookies to populate the cookie jar.
#HttpClient
interface HttpClient extends AsyncDisposableHTTP client interface.
| Name | Description |
|---|---|
config | Client 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
Client configuration
Methods
get(path: string, options?: HttpOptions): Promise<HttpResponse>Send GET request
Parameters
pathstringoptions?HttpOptions
head(path: string, options?: HttpOptions): Promise<HttpResponse>Send HEAD request
Parameters
pathstringoptions?HttpOptions
post(path: string, options?: HttpRequestOptions): Promise<HttpResponse>Send POST request
Parameters
pathstringoptions?HttpRequestOptions
put(path: string, options?: HttpRequestOptions): Promise<HttpResponse>Send PUT request
Parameters
pathstringoptions?HttpRequestOptions
patch(path: string, options?: HttpRequestOptions): Promise<HttpResponse>Send PATCH request
Parameters
pathstringoptions?HttpRequestOptions
delete(path: string, options?: HttpRequestOptions): Promise<HttpResponse>Send DELETE request
Parameters
pathstringoptions?HttpRequestOptions
options(path: string, options?: HttpOptions): Promise<HttpResponse>Send OPTIONS request
Parameters
pathstringoptions?HttpOptions
request(
method: string,
path: string,
options?: HttpRequestOptions,
): Promise<HttpResponse>Send request with arbitrary method
Parameters
methodstringpathstringoptions?HttpRequestOptions
getCookies(): Record<string, string>Get all cookies in the cookie jar. Returns empty object if cookies are disabled.
setCookie(name: string, value: string): voidSet a cookie in the cookie jar.
Parameters
namestringvaluestring
clearCookies(): voidClear all cookies from the cookie jar. No-op if cookies are disabled.
close(): Promise<void>Close the client and release resources
#HttpClientConfig
interface HttpClientConfig extends CommonOptionsHTTP client configuration.
| Name | Description |
|---|---|
url | Base URL for all requests. |
headers | Default headers for all requests |
fetch | Custom fetch implementation (for testing/mocking) |
redirect | Default redirect handling mode. |
throwOnError | Whether to throw HttpError for non-2xx responses. |
cookies | Cookie handling configuration. |
Properties
Base URL for all requests.
Can be a URL string or a connection configuration object.
- readonly
headers?HeadersInitDefault headers for all requests
- readonly
fetch?fetchCustom fetch implementation (for testing/mocking)
Default redirect handling mode. Can be overridden per-request via HttpOptions.
- readonly
throwOnError?booleanWhether to throw HttpError for non-2xx responses. Can be overridden per-request via HttpOptions.
#HttpConnectionConfig
interface HttpConnectionConfig extends CommonConnectionConfigHTTP connection configuration.
Extends CommonConnectionConfig with HTTP-specific options.
Properties
- readonly
protocol?"http" | "https"Protocol to use.
- readonly
path?stringBase path prefix for all requests.
#HttpErrorOptions
interface HttpErrorOptions extends ErrorOptionsOptions for creating an HttpError.
Properties
- readonly
body?Uint8Array | nullResponse body as raw bytes
- readonly
headers?Headers | nullResponse headers
#HttpOptions
interface HttpOptions extends CommonOptionsOptions for individual HTTP requests.
| Name | Description |
|---|---|
query | Query parameters (arrays for multi-value params) |
headers | Additional request headers |
redirect | Redirect handling mode. |
throwOnError | Whether to throw HttpError for non-2xx responses. |
Properties
Query parameters (arrays for multi-value params)
- readonly
headers?HeadersInitAdditional request headers
Redirect handling mode.
- readonly
throwOnError?booleanWhether to throw HttpError for non-2xx responses. When false, non-2xx responses are returned as HttpResponse.
#HttpRequestOptions
interface HttpRequestOptions extends HttpOptionsOptions for HTTP requests that may include a body.
| Name | Description |
|---|---|
body | Request body |
Properties
Request body
#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.
| Name | Description |
|---|---|
processed | Server processed the request. |
ok | Response was not successful (4xx/5xx). |
error | Error describing the HTTP error. |
status | HTTP status code (4xx/5xx). |
statusText | HTTP status text. |
headers | Response headers. |
raw | Raw Web standard Response. |
Properties
- readonly
processedtrueServer processed the request.
- readonly
okfalseResponse was not successful (4xx/5xx).
Error describing the HTTP error.
- readonly
statusnumberHTTP status code (4xx/5xx).
- readonly
statusTextstringHTTP status text.
- readonly
headersHeadersResponse headers.
- readonly
rawglobalThis.ResponseRaw Web standard Response.
#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.).
| Name | Description |
|---|---|
processed | Server did not process the request. |
ok | Request failed. |
error | Error describing the failure (ConnectionError, TimeoutError, AbortError). |
status | No HTTP status (request didn't reach server). |
statusText | No HTTP status text (request didn't reach server). |
headers | No headers (request didn't reach server). |
body | No body (request didn't reach server). |
raw | No raw response (request didn't reach server). |
Properties
- readonly
processedfalseServer did not process the request.
- readonly
okfalseRequest failed.
Error describing the failure (ConnectionError, TimeoutError, AbortError).
- readonly
statusnullNo HTTP status (request didn't reach server).
- readonly
statusTextnullNo HTTP status text (request didn't reach server).
- readonly
headersnullNo headers (request didn't reach server).
- readonly
bodynullNo body (request didn't reach server).
- readonly
rawnullNo raw response (request didn't reach server).
#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).
| Name | Description |
|---|---|
processed | Server processed the request. |
ok | Response was successful (2xx). |
error | No error for successful responses. |
status | HTTP status code (200-299). |
statusText | HTTP status text. |
headers | Response headers. |
raw | Raw Web standard Response. |
Properties
- readonly
processedtrueServer processed the request.
- readonly
oktrueResponse was successful (2xx).
- readonly
errornullNo error for successful responses.
- readonly
statusnumberHTTP status code (200-299).
- readonly
statusTextstringHTTP status text.
- readonly
headersHeadersResponse headers.
- readonly
rawglobalThis.ResponseRaw Web standard Response.
Functions
#createHttpClient
function createHttpClient(config: HttpClientConfig): HttpClientCreate 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
configHttpClientConfig- Client configuration including URL and default options
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
#BodyInit
type BodyInit = string | Uint8Array | FormData | URLSearchParams | unknownRequest body type.
#HttpFailureError
type HttpFailureError = HttpNetworkError | AbortError | TimeoutErrorError types that indicate the operation was not processed. These are errors that occur before the request reaches the server.
#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
#QueryParams
type QueryParams = URLSearchParams | Record<string, QueryValue | QueryValue[]>Query parameters type - accepts URLSearchParams or plain object.
#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
