Documentation v4.0.0

Overview

APIClient is an abstract base class for building API clients based on Axios. Extend this class to create domain-specific API clients with pre-configured base URL, timeout, and request interceptors.

Import

import {components} from 'metronic-extension';
const {APIClient} = components;

Constructor

new APIClient(path, origin?, options?)
Parameter Type Default Description
path string - Base path of the request URL. e.g. "/api/persons"
origin string location.origin Request URL origin. e.g. "https://example.com"
options AxiosRequestConfig - Additional Axios request config to merge with defaults (timeout: 60000, responseType: "json", withCredentials: true).

Properties

Property Type Description
client (protected) AxiosInstance The Axios instance used for making HTTP requests. Use this in subclass methods.

Methods

Method Return Description
getCancelToken() CancelTokenSource Returns an Axios cancellation token for aborting requests.
isCancel(thrown) boolean Returns true if the given error was caused by a cancelled request.

Basic Example

import {components} from 'metronic-extension';

class PersonApi extends components.APIClient {
  constructor() {
    super('/api/persons', 'https://example.com');
  }

  // POST https://example.com/api/persons
  async createPerson(formData) {
    return this.client.post('/', formData);
  }

  // PUT https://example.com/api/persons/:id
  async updatePerson(personId, formData) {
    return this.client.put(`/${personId}`, formData);
  }

  // GET https://example.com/api/persons/:id
  async getPerson(personId) {
    return this.client.get(`/${personId}`);
  }

  // DELETE https://example.com/api/persons/:id
  async deletePerson(personId) {
    return this.client.delete(`/${personId}`);
  }
}

const personApi = new PersonApi();
const res = await personApi.getPerson(1);