# @etsoo/restclient

> TypeScript REST client wrapup built-in Fetch

Latest version **1.1.40** (published 2026-08-24) · MIT license · 0 weekly downloads

## Install

```sh
npm install @etsoo/restclient
pnpm add @etsoo/restclient
yarn add @etsoo/restclient
bun add @etsoo/restclient
```

## Health

**Score 75/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; has provenance; recently updated; high maintenance score; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 1.1.40 |
| Published | 2026-08-24 |
| First published | 2020-08-07 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 175.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 2 |
| Author | Garry Xiao |
| Maintainers | garryxiao |
| Keywords | REST, API, fetch, TypeScript, ETSOO, SmartERP, 司友云平台, 青岛亿速思维, 上海亿商 |

## Links

- npm: https://www.npmjs.com/package/@etsoo/restclient
- Repository: https://github.com/ETSOO/restclient
- Homepage: https://github.com/ETSOO/restclient#readme
- Issues: https://github.com/ETSOO/restclient/issues
- npm.io page: https://npm.io/package/@etsoo/restclient

## Dependencies (1)

- [@etsoo/shared](https://npm.io/package/@etsoo/shared.md) ^1.2.91

## Alternatives

- [launchdarkly-js-client-sdk](https://npm.io/package/launchdarkly-js-client-sdk.md) — 2.5M weekly downloads
- [@elastic/elasticsearch](https://npm.io/package/@elastic/elasticsearch.md) — 2.1M weekly downloads
- [@c8y/client](https://npm.io/package/@c8y/client.md) — 15.3K weekly downloads
- [@signaldb/maverickjs](https://npm.io/package/@signaldb/maverickjs.md) — 1.7K weekly downloads
- [@bbc/http-transport-cache](https://npm.io/package/@bbc/http-transport-cache.md) — 1.2K weekly downloads

## Recent versions

- 1.1.40 (latest) — 2026-08-24
- 1.1.39 — 2026-07-11
- 1.1.38 — 2026-07-11
- 1.1.37 — 2026-06-26
- 1.1.36 — 2026-05-09
- 1.1.35 — 2026-04-05
- 1.1.34 — 2026-03-29
- 1.1.33 — 2025-11-05
- 1.1.32 — 2025-11-04
- 1.1.31 — 2025-09-16
- 1.1.30 — 2025-06-10
- 1.1.29 — 2025-05-26
- 1.1.28 — 2025-05-09
- 1.1.27 — 2025-04-16
- 1.1.26 — 2025-04-01
- … 123 more at https://npm.io/package/@etsoo/restclient/versions

## README

# @etsoo/restclient

**TypeScript promise based HTTP/REST API client.**

- fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
- node-fetch: https://github.com/node-fetch/node-fetch

Vitest applied, supports CommonJs and ESM. About how to build a NPM package and CI/CD with Github action: https://dev.to/garryxiao/build-a-react-components-npm-package-and-ci-cd-with-github-action-1jm6

Includes FetchLikeApi for extension quickly:

```ts
/**
 * Fetch API
 */
export class FetchApi extends FetchLikeApi<Response> {
  constructor() {
    super(fetch);
  }
}

// Under Node
// install node-fetch (https://github.com/node-fetch/node-fetch) first, and @types/node-fetch with TypeScript
const { FetchLikeApi } = require("@etsoo/restclient");
const fetch,
  { Response } = require("node-fetch");
class FetchApi extends FetchLikeApi<Response> {
  constructor() {
    super(fetch);
  }
}
```

## Installing

Using npm:

```bash
$ npm install @etsoo/restclient
```

Using yarn:

```bash
$ yarn add @etsoo/restclient
```

## Example

### Initialization

- Depending on the envioronment, fetch first.
- Under node, supports node-fetch.

```ts
import { createClient } from "@etsoo/restclient";
const client = createClient();

// Or
import { createClientAsync } from "@etsoo/restclient";
const client = await createClientAsync();
```

- Depending on your decision.

```ts
import { FetchApi } from "@etsoo/restclient";
const client = new FetchApi();
```

### Calls

```ts
// Customer data structure
interface Customer {
  id: string;
  name: string;
}

// API client
const client = createClient();

// Authorization, JWT
client.authorize(ApiAuthorizationScheme.Bearer, "*** JWT token ***");

// Read customer list with asyc/await ES6+ style
const customers = await client.get<Customer[]>("/api/customer");
// or with traditional callback way
client.get<Customer[]>("/api/customer").then((customers) => {});

// Read one customer
const customer = await client.get<Customer>("/api/customer/1");
if (customer == null) {
  // Error found
  return;
}
console.log(customer.name);
```

### Error handling

```ts
// API client
const client = createClient();

// Global error handling
client.onError = (error) => {
  console.log(error);
};

// Read one customer
var payload: IApiPayload<Customer, any> = {
  // Current call's error handling
  onError = (error) => {
    console.log(error);
    // return false to prevent further error handling
    return false;
  },
  // Pass default value to distinguish return value with error or undefined
  defaultValue: {}
};

const customer = await client.get<Customer>(
  "/api/customer/1",
  undefined,
  payload
);
if (customer == null) {
  // Error found
  // client.lastError cache the last error
  // For accurate check, validate client.lastError.data.url
  return;
}

// Now call payload.response to access headers
// client.transformResponse(payload.response) to get a standard IApiResponse
```

## Properties

|                Name | Description                                    |
| ------------------: | ---------------------------------------------- |
|             baseUrl | API base URL, add to the API root of all calls |
|             charset | Charset for sending data, default is 'utf-8'   |
|              config | See Request Config or fetch/RequestInit        |
| defaultResponseType | Default type is JSON                           |
|     jsonContentType | JSON content type string, 'application/json'   |
|           lastError | Last error for track                           |
|                name | The name of the API, default value is 'system' |
|             onError | Error occured callback                         |
|           onRequest | Before request callback                        |
|          onComplete | After request completed but before onResponse  |
|          onResponse | After response callback                        |

## Methods

Provides **delete, get, head, options, patch, post, put** syntactic sugar for **request** method. Return with **undefined** means error found. If the API return nothing with success, a **empty object {}** will be returned to distingush the error case. Define a **onError** callback function at **payload** only for the call or client's property **onError** for global error handling.

```ts
    /**
     * Authorize the call
     * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
     * @param scheme Scheme
     * @param token Token, empty/null/undefined to remove it
     * @param writeHeaders Headers to write authtication, default to all calls
     */
    authorize(
        scheme: ApiAuthorizationScheme | string,
        token: string | undefined,
        writeHeaders?: HeadersInit
    ): void;

    /**
     * Detect IP data
     * @param ip IP address or query URLs
     * @returns IP data
     */
    detectIP(ip?: string | URL | string[]): Promise<IPData | undefined>;

    /**
     * Get authorization header value
     * @returns Authorization header value
     */
    getAuthorization(): { scheme: string; token: string } | undefined;

    /**
     * Get HTTP content dispostion
     * @param responseOrValue Response or header value
     * @returns Result
     */
    getContentDisposition(response: R): ContentDisposition | undefined;
    getContentDisposition(header: string): ContentDisposition | undefined;

    /**
     * Get content length
     * @param headers Headers
     * @returns
     */
    getContentLength(headers: HeadersAll): number | undefined;

    /**
     * Get content type and charset
     * @param headers Headers
     */
    getContentTypeAndCharset(headers: HeadersInit): [string, string?];

    /**
     * Get content type
     * @param headers Headers
     */
    getHeaderValue(headers: HeadersInit, key: string): string | null;

    /**
     * Get Json data directly
     * @param url URL
     * @returns Json data
     */
    getJson<T = DataTypes.ReadonlyData>(url: string): Promise<T>;

    /**
     * Get status text
     * @param status Status code
     * @returns Status text
     */
    getStatusText(status: number): string;

    /**
     * Request to API
     * @param method Method
     * @param url API URL
     * @param data Passed data
     * @param payload Payload
     */
    request<T>(
        method: ApiMethod,
        url: string,
        data?: ApiRequestData,
        payload?: IApiPayload<T, R>
    ): Promise<T | undefined>;

    /**
     * Set content language
     * @param language Content language
     * @param headers Headers, default is global headers
     */
    setContentLanguage(
        language: string | null | undefined,
        headers?: HeadersInit
    ): void;

    /**
     * Set header value
     * @param key Header name
     * @param value Header value
     * @param headers Headers to lookup
     */
    setHeaderValue(
        key: string,
        value: string | null | undefined,
        headers: HeadersInit
    ): void;

    /**
     * Transform the original response to a unified object
     * @param response Original response
     */
    transformResponse(response: R): IApiResponse;
```

## Call Payload

When you call any API, pass additional properties with the payload parameter.

|         Name | Description                                                                      |
| -----------: | -------------------------------------------------------------------------------- |
|  contentType | Specify data type to send, like 'application/json'                               |
|      onError | Current API call error callback                                                  |
|       config | Current API config. See Request Config or fetch/RequestInit                      |
| defaultValue | Default value, like [] for array return to distinguish undefined or error return |
|       params | URL parameters                                                                   |
|       parser | Current API response data parser                                                 |
|     response | Request response object                                                          |
| responseType | Specify response data type                                                       |
|  showLoading | Whether to show loading bar                                                      |
|        local | Local URL and ignore baseUrl                                                     |

## License

[MIT](LICENSE)

---
_Source: https://npm.io/package/@etsoo/restclient · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
