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
, andDELETE
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
Parameter | Type | Description |
---|---|---|
baseUrl | string | The base URL for all API requests (e.g., https://api.example.com ). |
defaultHeaders | Record<string, string> | Optional headers included in every request. Default includes Content-Type: application/json . |
options | RestClientOptions | Optional 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:
Hook | Signature | Description |
---|---|---|
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:
Method | Description | Returns | Link |
---|---|---|---|
setHeaders | Updates default headers (e.g. Authorization). | void | setHeaders |
getAsync | Sends a GET request with optional query params. | Promise<any> | getAsync |
postAsync | Sends a POST request with a JSON body. | Promise<any> | postAsync |
putAsync | Sends a PUT request with a JSON body. | Promise<any> | putAsync |
patchAsync | Sends a PATCH request with a JSON body. | Promise<any> | patchAsync |
deleteAsync | Sends a DELETE request. | Promise<any> | deleteAsync |
Each method supports optional headers and AbortController
for cancellation.