# @vkhalikov/rest-api-client

> A basic, extendable REST API Client

Latest version **0.3.1** (published 2021-04-17) · MIT license · 0 weekly downloads

## Install

```sh
npm install @vkhalikov/rest-api-client
pnpm add @vkhalikov/rest-api-client
yarn add @vkhalikov/rest-api-client
bun add @vkhalikov/rest-api-client
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.3.1 |
| Published | 2021-04-17 |
| First published | 2021-03-27 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 22.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Vadim Khalikov |
| Maintainers | vkhalikov |
| Keywords | rest, api |

## Links

- npm: https://www.npmjs.com/package/@vkhalikov/rest-api-client
- Repository: https://github.com/vkhalikov/rest-api-client
- Homepage: https://github.com/vkhalikov/rest-api-client#readme
- Issues: https://github.com/vkhalikov/rest-api-client/issues
- npm.io page: https://npm.io/package/@vkhalikov/rest-api-client

## Dependencies (1)

- [query-string](https://npm.io/package/query-string.md) ^7.0.0

## 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

- 0.3.1 (latest) — 2021-04-17
- 0.3.0 — 2021-04-11
- 0.2.1 — 2021-04-03
- 0.2.0 — 2021-03-28
- 0.1.0 — 2021-03-27

## README

# REST API Client

A basic, extendable client for your REST API.

## Installation

```bash
npm install --save @vkhalikov/rest-api-client
```

## Basic usage

```javascript
// resources/todos.js
import { Resource } from '@vkhalikov/rest-api-client';

export const todos = new Resource('todos');
```

```javascript
// api.js
import Client from '@vkhalikov/rest-api-client';
import { todos, posts, users } from './resources';

const API_URL = 'https://api.mysite.com';

const resources = [todos, posts];

const api = new Client(API_URL, { resources });

api.route('rest/v2', { resources: [users] });

export default api;
```

```javascript
// app.js
import api from './api.js';

let todos;

// final url: "https://api.mysite.com/todos"
api.todos.getAll()
  .then((data) => {
    todos = data;
  })
  .catch((err) => {
    handleError(err);
  });

// You don't have to worry about serialization
// Request body will be automatically serialized with JSON.parse(),
// if 'Content-Type' header contains 'json', which is a default header
const newPost = {
  title: 'Amazing Post',
  message: 'Hello, Worm!',
};

// final url: "https://api.mysite.com/posts"
api.posts.create({ body: newPost });

// final url: "https://api.mysite.com/rest/v2/users/001"
api.users.getById(001);

let adminPosts;

// final url: "https://api.mysite.com/posts/?userId=001"
api.posts.get({ query: { userId: 001 } })
  .then((data) => adminPosts = data)
  .catch((err) => {
    handleError(err);
  });

// You can also make requests directly
api.post('posts', { body: newPost });
```

## API

#### `Client`

##### `constructor(baseURL, { resources, authToken, defaultFetchOptions, bodyParser, onError }): Client`

###### Arguments

|       Argument        | Required |                                Type                                 |               Default Value              | Description                                                                                                                                                                                                                       |
|:---------------------:|:--------:|:-------------------------------------------------------------------:|:----------------------------------------:|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|       `baseURL`       |     ✔    |                              `string`                               |                `undefined`               | URL of your API.                                                                                                                                                                                                                  |
|      `resources`      |          |                             `[Resource]`                            |                   `[]`                   | An array of Resources. Each resource becomes an Client instance property. Example: Resource with `name` `"todos"` will be available as `api.todos` property.                                                                   |
|      `authToken`      |          |                             `AuthToken`                             |                `undefined`               | An instance of `AuthToken`. For more detailed information see [`AuthToken`](#authtoken)                                                                                                                                           |
| `defaultFetchOptions` |          |                              `object`                               | `{ 'Content-Type': 'application/json' }` | Will be added to fetch options with every request.                                                                                                                                                                                |
|      `bodyParser`     |          | `string` `or` `function(body: Body, requestMethod:string): Promise` | `(body) => body.json()`   | A function that will return a parsed body depending on a requestMethod. If a string is passed, one of predefined body parsers will be used. Valid string options: `json`, `arrayBuffer`, `blob`, `text`, `formData`.              |
|      `onError`        |          |                        `function(error): void`                      |                `undefined`               | A function that will handle response errors if `Response.ok === false`.  Pass it if you want to specify your own error types depending on response statuses or another information that your API provides, or maybe you want to handle them in one place.           |

---

##### Methods

A basic methods, which are you used to create requests with according HTTP methods.
You can use them for a specific calls to your API, or if you don't need any `Resources`.
##### `get(path, options): Promise`
##### `post(path, options): Promise`
##### `patch(path, options): Promise`
##### `put(path, options): Promise`
##### `delete(path, options): Promise`

###### Arguments

|        Argument       | Required |          Type          | Default Value | Description                                                                                                                                                                                                              |
|:---------------------:|:--------:|:----------------------:|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|         `path`        |     ✔    |        `string`        |  `undefined`  | A path to a resource. The result URL will be `{baseURL}/{path}?{query}`.                                                                                                                                                 |
|    `options.query`    |          | `string` `or` `object` |  `undefined`  | Passing this option will result in adding the `query` part to the final URL. If `string` it will be passed as is. If `object` it will be stringified using [`query-string`](https://www.npmjs.com/package/query-string). |
| `options: {...rest}` |          |                         |      `{}`     | Rest options are considered `fetch()` options.                                                                                                                                                                              |

---

##### `route(path: String, options): void`

###### Arguments

|        Argument       | Required |          Type          | Default Value | Description                                                                                            |
|:---------------------:|:--------:|:---------------------:|:--------------:|--------------------------------------------------------------------------------------------------------|
|         `path`        |     ✔    |        `string`        |  `undefined`  | A path to a group of resources. All resources passed to this route will be sending requests to a specified path.                                                    |
|      `resources`      |          |      `[Resource]`      |      `[]`     | Same as for [`Client`](#client)                                                   |

---

##### `setAuthToken(authToken: AuthToken): void`

###### Arguments

|   Argument  | Required |     Type    | Default Value | Description                                                                                            |
|:-----------:|:--------:|:-----------:|:-------------:|--------------------------------------------------------------------------------------------------------|
| `authToken` |     ✔    | `AuthToken` |  `undefined`  | An instance of [`AuthToken`](#authtoken). Will be passed in `Authorization` header with every request. |                                                                                                        |

---

##### `resetAuthToken(): void`

Sets authToken to `null`

---

##### `injectResources(resources: [Resource]): void`

Manual resource injection.

###### Arguments

|   Argument  | Required |     Type     | Default Value | Description                                                                                                                                                                    |
|:-----------:|:--------:|:------------:|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `resources` |     ✔    | `[Resource]` |  `undefined`  | An array of [`Resources`](#resource). Each resource becomes an Client instance property. Example: Resource with `name` `"todos"` will be available as `api.todos` property. |                                         |

---

#### `Resource`

##### `constructor(name, { defaultFetchOptions, bodyParser }): Resource`

|        Argument       | Required |                                 Type                                | Default Value | Description                                                                                                                                    |
|:---------------------:|:--------:|:-------------------------------------------------------------------:|:-------------:|------------------------------------------------------------------------------------------------------------------------------------------------|
|         `name`        |     ✔    |                               `string`                              |  `undefined`  | A name of Resource. This defines a name by which a Resource will be available after injection. A name also becomes a `path` for every request. |
| `defaultFetchOptions` |          |                               `object`                              |  `undefined`  | Same as `Client.defaultFetchOptions` and will be merged with them but takes precedence.                                                     |
|      `bodyParser`     |          | `string` `or` `function(requestMethod:string, body: Body): Promise` |  `undefined`  | Same as `Client.bodyParser`. If passed, will be used instead of `Client.bodyParser` for this Resource.                                   |
|         `path`        |          |                               `string`                              |  `undefined`  | A path to a resource. Overwrites the default path resolution behaviour (by a resource name).                                   |

---

##### Methods

##### `get({ id, query, ...fetchOptions }): Promise`
##### `getById(id, { query, ...fetchOptions }): Promise`
##### `getAll({ query, ...fetchOptions }): Promise`
##### `create({ body, ...fetchOptions }): Promise`
##### `update({ id, query, body, ...fetchOptions }): Promise`
##### `replace({ id, query, body, ...fetchOptions }): Promise`
##### `delete({ id, query, ...fetchOptions }): Promise`

###### Arguments

|    Argument    | Required |          Type          | Default Value | Description                                                                                   |
|:--------------:|:--------:|:----------------------:|:-------------:|-----------------------------------------------------------------------------------------------|
|      `id`      |          |        `string`        |  `undefined`  | An ID of a requested resource. Will be added to a final URL: `{baseURL}/{resourceName}/{id}`. |
|     `query`    |          | `string` `or` `object` |  `undefined`  | Same as for [`Client`](#client) requests.                                               |
|     `body`     |     ✔    |  `any` valid body type |  `undefined`  | A request body. Examples: `string`, `formData`, `blob`, etc.                                  |
| `fetchOptions` |          |        `object`        |  `undefined`  | Same as `Resource.defaultFetchOptions` and will be merged with them but takes precedence.     |

---

#### `AuthToken`

Used in [`Client`](#client). Will be passed in `Authorization` header with every request.

Example: AuthToken with `authScheme` `Basic` and `body` `Base64EncodedToken` will become `Authorization: Basic Base64EncodedToken` header.

##### `constructor(body, { authScheme }): AuthToken`

###### Arguments

|    Argument    | Required |          Type         | Default Value | Description                                                                                                                                                        |
|:--------------:|:--------:|:---------------------:|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|     `body`     |          |        `string`       |  `undefined`  | A token body. Usually base64 encoded.                                                                                                                              |
|  `authScheme`  |          |        `string`       |    `Basic`    | An auth scheme. For more detalied information see [IANA list of authentication schemes](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml). |


---

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