Skip to main content

RestClient

RestClient provides a clean, flexible abstraction to interact with RESTful APIs via HTTP methods. It supports GET, POST, PUT, PATCH, and DELETE requests with JSON or text response handling, customizable headers, request timeout, and optional retries for transient errors.


Features

  • Supports GET, POST, PUT, PATCH, and DELETE methods.
  • Automatically handles JSON and text responses.
  • Customizable default headers.
  • Configurable timeout and retry mechanism.
  • Lifecycle hooks for logging or custom behaviors.
  • Clean URL and query parameter handling.

Constructor

constructor(
baseUrl: string,
defaultHeaders?: Record<string, string>,
options?: RestClientOptions
)
  • baseUrl: Base URL for all API requests (e.g., https://api.example.com).
  • defaultHeaders: Optional default headers included in every request.
  • options: Configuration such as timeout, max retries, retry policy, delay function, and hooks through RestClientOptions.

Parameters

ParameterTypeDescription
baseUrlstringThe base URL for all API requests (e.g., https://api.example.com).
defaultHeadersRecord<string, string>Optional headers included in every request. Default includes Content-Type: application/json.
optionsRestClientOptionsOptional configuration to control timeout, retries, and request hooks.

Example

const client = new RestClient("https://api.example.com", {
Authorization: "BEARER_TOKEN"
}, {
timeout: 15000,
maxRetries: 2,
onRequestStart: (method, url) => console.log(`Starting ${method} ${url}`)
});

Internal Behavior

Default Headers

All requests include:

{
"Content-Type": "application/json",
...yourHeaders
}

Timeout

Requests time out after the specified duration (default: 10000ms).

Retry Logic

If enabled (maxRetries > 0), failed requests will be retried based on:

shouldRetry: (res) => [502, 503, 504].includes(res.status)

You can override this by providing a custom shouldRetry function.

Delay Function

The delay between retries can be customized with the delayFn. By default, it uses:

(ms) => new Promise(resolve => setTimeout(resolve, ms))

Or you can plug in your own exponential backoff implementation.

Lifecycle Hooks

These optional hooks provide fine-grained control or logging over the request lifecycle:

HookSignatureDescription
onRequestStart(method: string, url: string, options: RequestInit)Called before sending a request.
onRequestEnd(response: Response)Called after a successful response.
onRequestError(error: unknown)Called when a request fails due to an exception.

Methods

The RestClient class provides the following async methods:

MethodDescriptionReturnsLink
setHeadersUpdates default headers (e.g. Authorization).voidsetHeaders
getAsyncSends a GET request with optional query params.Promise<any>getAsync
postAsyncSends a POST request with a JSON body.Promise<any>postAsync
putAsyncSends a PUT request with a JSON body.Promise<any>putAsync
patchAsyncSends a PATCH request with a JSON body.Promise<any>patchAsync
deleteAsyncSends a DELETE request.Promise<any>deleteAsync

Each method supports optional headers and AbortController for cancellation.