Skip to main content

GET Request

The getAsync method sends an HTTP GET request to the specified endpoint. It supports optional route parameters, query parameters, custom headers, and request cancellation via an AbortController.


Method Signature

public async getAsync(
routeParam?: string | null,
queryParams?: Record<string, any>,
headers?: Record<string, string>,
controller?: AbortController | null
): Promise<any>

Parameters

NameTypeDescriptionOptionalDefault Value
routeParamstring | nullOptional route segment to append to the base URLYesnull
queryParamsRecord<string, any>Optional key-value pairs to be appended as URL query parametersYes{}
headersRecord<string, string>Optional HTTP headers to include in the requestYes{}
controllerAbortController | nullOptional controller to allow request cancellationYesnull

Returns

The getAsync method returns a Promise that resolves to one of the following, depending on the server response:

  • Parsed JSON object if the response has a Content-Type of application/json
  • Plain text string if the response is text-based
  • null if the server responds with HTTP status 204 No Content

Error Handling

If the request fails, the returned Promise rejects with an error object containing:

  • message: A descriptive error message
  • status: HTTP status code (if available)
  • statusText: HTTP status text (if available)
  • responseBody: Parsed response body or raw text for further inspection

Errors can occur due to network failures, request timeouts, server errors, or manual request cancellation (via AbortController).

Example

import RestClient from '@bishal-shrestha/rest-client';

const client = new RestClient('https://api.example.com', {
Authorization: 'Bearer YOUR_TOKEN',
});

async function run(): Promise<void> {
try {
const users: any = await client.getAsync('users');
console.log('Users:', users);
} catch (error: unknown) {
console.error('GET request failed:', error);
}
}

run();