RestApi

RestApi Utility class for REST Api development wraps native fetch internally.

Constructor

new RestApi(url, headersopt, optionsopt)

Constructor

Parameters:
NameTypeAttributesDescription
urlstring

Base url

headersHeaders<optional>

Header data.

optionsobject<optional>

Configuration options

Properties
NameTypeAttributesDescription
timeoutnumber<optional>

Request timeout in milliseconds (default: 30000)

retryAttemptsnumber<optional>

Number of retry attempts (default: 0)

retryDelaynumber<optional>

Delay between retries in milliseconds (default: 1000)

Examples

Using callbacks

const myRestApi = new RestApi( 'https://api.example.com' );
myRestApi.get( '/books', function( err, result ) { } );

Using await

const myRestApi = new RestApi( 'https://api.example.com' );
try
{
    const result = await myRestApi.get( '/books' );
}
catch( e )
{
    // Handle error
}

With timeout and retry configuration

const myRestApi = new RestApi( 'https://api.example.com', {}, {
    timeout: 10000,      // 10 second timeout
    retryAttempts: 3,    // Retry up to 3 times
    retryDelay: 1000     // Wait 1 second between retries
});

Per-request timeout and retry override

const result = await myRestApi.get('/books', null, {
    timeout: 5000,       // Override to 5 second timeout
    retryAttempts: 1     // Override to 1 retry attempt
});

Headers management

myRestApi.addHeader('Authorization', 'Bearer token123');
myRestApi.addHeader('Content-Type', 'application/json');
myRestApi.removeHeader('Content-Type');
const headers = myRestApi.getHeaders(); // Get copy of current headers

Query parameters

// Simple query parameters
const books = await myRestApi.get('/books', null, {
    queryParams: { page: 1, limit: 10, search: 'javascript' }
});
// Results in: GET /books?page=1&limit=10&search=javascript

// Array parameters
const filtered = await myRestApi.get('/books', null, {
    queryParams: { tags: ['fiction', 'drama'], author: 'Shakespeare' }
});
// Results in: GET /books?tags=fiction&tags=drama&author=Shakespeare

Request cancellation

// Make a request and get the request ID
const { requestId, result } = await myRestApi.get('/large-data');

// Make a request with callback and get request ID immediately
const { requestId } = await myRestApi.get('/books', (err, result) => {
    if (err) console.error('Request failed:', err);
    else console.log('Books:', result);
});

// Cancel the specific request
const cancelled = myRestApi.cancelRequest(requestId);
console.log('Request cancelled:', cancelled);

// Check if request is still pending
if (myRestApi.isRequestPending(requestId)) {
    console.log('Request is still running');
}

// Get all pending requests
const pending = myRestApi.getPendingRequests();
console.log('Pending requests:', pending);

// Cancel all requests
myRestApi.abortAll();

Progress tracking

// Upload progress tracking
const formData = new FormData();
formData.append('file', fileInput.files[0]);

const { requestId } = await myRestApi.post('/upload', formData, null, {
    onUploadProgress: (progress) => {
        console.log(`Upload: ${progress.percent}% (${progress.loaded}/${progress.total} bytes)`);
        // Update progress bar: progressBar.value = progress.percent;
    }
});

// Download progress tracking
const { requestId, result } = await myRestApi.get('/large-file', null, {
    onDownloadProgress: (progress) => {
        console.log(`Download: ${progress.percent}% (${progress.loaded}/${progress.total} bytes)`);
        // Update progress bar: downloadBar.value = progress.percent;
    }
});

// Both upload and download progress
const { requestId } = await myRestApi.put('/documents/123', documentData, null, {
    onUploadProgress: (progress) => {
        console.log('Uploading:', progress.percent + '%');
    },
    onDownloadProgress: (progress) => {
        console.log('Downloading response:', progress.percent + '%');
    }
});

Methods

_buildQueryString(params) → {string}

Build query string from parameters object

Parameters:
NameTypeDescription
paramsobject

Query parameters object

Returns:

Query string (without leading ?)

Type: 
string

_buildUrl(endpoint, queryParamsopt) → {string}

Build complete URL with query parameters

Parameters:
NameTypeAttributesDefaultDescription
endpointstring

API endpoint

queryParamsobject<optional>
null

Query parameters object

Returns:

Complete URL

Type: 
string

abortAll()

Aborts all pending requests

addHeader(name, value)

Add or update a base header

Parameters:
NameTypeDescription
namestring

Header name

valuestring

Header value

cancelRequest(requestId) → {boolean}

Cancel a specific request by ID

Parameters:
NameTypeDescription
requestIdstring

The request ID to cancel

Returns:

True if request was found and cancelled, false otherwise

Type: 
boolean

(async) delete(endpoint, cbopt, optionsopt) → {Promise.<{requestId: string, result: (any|undefined)}>}

DELETE call

Parameters:
NameTypeAttributesDefaultDescription
endpointstring

API endpoint

cbfunction<optional>
null

Callback function

optionsobject<optional>
{}

Request options

Properties
NameTypeAttributesDescription
timeoutnumber<optional>

Request timeout in milliseconds

retryAttemptsnumber<optional>

Number of retry attempts

retryDelaynumber<optional>

Delay between retries in milliseconds

queryParamsobject<optional>

Query parameters object

onDownloadProgressfunction<optional>

Download progress callback

Returns:

Promise with request ID and result (if no callback)

Type: 
Promise.<{requestId: string, result: (any|undefined)}>

(async) get(endpoint, cbopt, optionsopt) → {Promise.<{requestId: string, result: (any|undefined)}>}

GET call

Parameters:
NameTypeAttributesDefaultDescription
endpointstring

API endpoint

cbfunction<optional>
null

Callback function

optionsobject<optional>
{}

Request options

Properties
NameTypeAttributesDescription
timeoutnumber<optional>

Request timeout in milliseconds

retryAttemptsnumber<optional>

Number of retry attempts

retryDelaynumber<optional>

Delay between retries in milliseconds

queryParamsobject<optional>

Query parameters object

onDownloadProgressfunction<optional>

Download progress callback

Returns:

Promise with request ID and result (if no callback)

Type: 
Promise.<{requestId: string, result: (any|undefined)}>

getHeaders() → {Headers}

Get all current base headers

Returns:

Current headers object

Type: 
Headers

getPendingRequests() → {Array.<string>}

Get all pending request IDs

Returns:

Array of pending request IDs

Type: 
Array.<string>

isRequestPending(requestId) → {boolean}

Check if a request is still pending

Parameters:
NameTypeDescription
requestIdstring

The request ID to check

Returns:

True if request is still pending

Type: 
boolean

(async) patch(endpoint, dataopt, cbopt, optionsopt) → {Promise.<{requestId: string, result: (any|undefined)}>}

PATCH call

Parameters:
NameTypeAttributesDefaultDescription
endpointstring

API endpoint

dataobject<optional>
{}

Patch data

cbfunction<optional>
null

Callback function

optionsobject<optional>
{}

Request options

Properties
NameTypeAttributesDescription
timeoutnumber<optional>

Request timeout in milliseconds

retryAttemptsnumber<optional>

Number of retry attempts

retryDelaynumber<optional>

Delay between retries in milliseconds

queryParamsobject<optional>

Query parameters object

onUploadProgressfunction<optional>

Upload progress callback

onDownloadProgressfunction<optional>

Download progress callback

Returns:

Promise with request ID and result (if no callback)

Type: 
Promise.<{requestId: string, result: (any|undefined)}>

(async) post(endpoint, dataopt, cbopt, optionsopt) → {Promise.<{requestId: string, result: (any|undefined)}>}

POST call

Parameters:
NameTypeAttributesDefaultDescription
endpointstring

API endpoint

dataobject<optional>
{}

Post data

cbfunction<optional>
null

Callback function

optionsobject<optional>
{}

Request options

Properties
NameTypeAttributesDescription
timeoutnumber<optional>

Request timeout in milliseconds

retryAttemptsnumber<optional>

Number of retry attempts

retryDelaynumber<optional>

Delay between retries in milliseconds

queryParamsobject<optional>

Query parameters object

onUploadProgressfunction<optional>

Upload progress callback

onDownloadProgressfunction<optional>

Download progress callback

Returns:

Promise with request ID and result (if no callback)

Type: 
Promise.<{requestId: string, result: (any|undefined)}>

(async) put(endpoint, dataopt, cbopt, optionsopt) → {Promise.<{requestId: string, result: (any|undefined)}>}

PUT call

Parameters:
NameTypeAttributesDefaultDescription
endpointstring

API endpoint

dataobject<optional>
{}

PUT data

cbfunction<optional>
null

Callback function

optionsobject<optional>
{}

Request options

Properties
NameTypeAttributesDescription
timeoutnumber<optional>

Request timeout in milliseconds

retryAttemptsnumber<optional>

Number of retry attempts

retryDelaynumber<optional>

Delay between retries in milliseconds

queryParamsobject<optional>

Query parameters object

onUploadProgressfunction<optional>

Upload progress callback

onDownloadProgressfunction<optional>

Download progress callback

Returns:

Promise with request ID and result (if no callback)

Type: 
Promise.<{requestId: string, result: (any|undefined)}>

removeHeader(name)

Remove a base header

Parameters:
NameTypeDescription
namestring

Header name to remove

setHeaders(headers)

Set multiple headers at once

Parameters:
NameTypeDescription
headersobject | Headers

Headers to set