# @sagacify/api-reader

> REST API request handler

Latest version **2.2.1** (published 2022-05-23) · MIT license · 0 weekly downloads

> **Deprecated.** This package is deprecated.

## Install

```sh
npm install @sagacify/api-reader
pnpm add @sagacify/api-reader
yarn add @sagacify/api-reader
bun add @sagacify/api-reader
```

## Health

**Score 10/100 (F)** — status: deprecated.

Negative: deprecated.

## Facts

| | |
|---|---|
| Version | 2.2.1 |
| Published | 2022-05-23 |
| First published | 2020-11-25 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 23.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | @oliviercuyp |
| Maintainers | sagacify |
| Keywords | api, json, request, requests, fetch |

## Links

- npm: https://www.npmjs.com/package/@sagacify/api-reader
- npm.io page: https://npm.io/package/@sagacify/api-reader

## Dependencies (2)

- [qs](https://npm.io/package/qs.md) ^6.9.4
- [node-fetch](https://npm.io/package/node-fetch.md) ^2.6.1

## Alternatives

- [@mapbox/jsonlint-lines-primitives](https://npm.io/package/@mapbox/jsonlint-lines-primitives.md) — 5.3M weekly downloads
- [reftools](https://npm.io/package/reftools.md) — 3.5M weekly downloads
- [@hey-api/openapi-ts](https://npm.io/package/@hey-api/openapi-ts.md) — 3.5M weekly downloads
- [@mapbox/geojson-rewind](https://npm.io/package/@mapbox/geojson-rewind.md) — 2.4M weekly downloads
- [turbo-stream](https://npm.io/package/turbo-stream.md) — 1.7M weekly downloads

## Recent versions

- 2.2.1 (latest) — 2022-05-23
- 2.2.0 — 2020-12-02
- 2.1.0 — 2020-12-02
- 2.0.0 — 2020-12-01
- 1.1.2 — 2020-11-25
- 1.1.1 — 2020-11-25
- 1.1.0 — 2020-11-25

## README

# ApiReader

:warning: This package is deprecated in favor of [Wretch](https://www.npmjs.com/package/wretch) :warning:

[![CircleCI](https://circleci.com/gh/Sagacify/api-reader.svg?style=svg)](https://circleci.com/gh/Sagacify/api-reader)
[![Coverage Status](https://coveralls.io/repos/github/Sagacify/api-reader/badge.svg?branch=main)](https://coveralls.io/github/Sagacify/api-reader?branch=main)
[![npm version](https://img.shields.io/npm/v/@sagacify/api-reader.svg)](https://www.npmjs.com/package/@sagacify/api-reader)

## Description

ApiReader is a NodeJS & Browser package meant to simplify your requests to any Api.
Browser version is based on native fetch to be as tiny as possible if you use treechecking in your toolbelt (like webpack, create-react-app, ...).
It features:

- API base url recording at constuction for smaller calls
- automatic query string stringification (based on qs)
- automatic request body JSON stringifying based body type (objects are stringified)
- automatic response body JSON parsing based on the Content-Type of the Api response
- automatic base64 encoding on Basic Authentication
- custom http error handling hook

## Acknowledgment

Most of the code structure and part of the code is inspired from the great [bent package](https://github.com/mikeal/bent/).
If you don't know it, check it out !

## Installation

```sh
$ npm install @sagacify/api-reader
```

## Usage

### In your project (Browser or NodeJS)

```js
const { ApiReader } = require('@sagacify/api-reader');
// OR
import { ApiReader } from '@sagacify/api-reader';

const main = () => {
  const bearerToken = 'super-secret-token';
  const apiReader = new ApiReader('https://api.twitter.com/2/', {
    headers: {
      authorization: `Bearer ${bearerToken}`
    },
    httpErrorHandler: (req, res) => {
      console.error(`My custom error ${res.status} for ${req.method} on ${req.url}`)
    }
  });

  try {
    const result = await apiReader.get('/2/tweets', {
      query: {
        id: 'some-tweet-id'
      },
    });

    console.log(result);
  } catch (err) {
    // This is an unexpected error, like an network issue
    console.error(err);
  }
}

main();
```

> Note: based on the context either the Browser or the NodeJS version will be used

### API

#### constructor(baseUrl, options)

##### Parameters

- **baseUrl**: the base url of the api (e.g.: <https://api.twitter.com/2/>)
- **options**:
  - **auth**:
    - **username**: the username of the Basic Authentication
    - **password**: the password of the Basic Authentication
  - **headers**:
    - **[header-name]**: header value
  - **queryOptions**: query stringification is based on the [qs stringify](https://www.npmjs.com/package/qs#stringifying) package, here you can pass any qs option you need
  - **preRequestHandler**: a pre-request handler function which recieve the fetch options and must return the final fetch options:

    ```js
    {
      method: <string>, // in uppercase
      headers: <Headers>, // see: https://developer.mozilla.org/fr/docs/Web/API/Headers
      body: <string | object>
    }
    ```

    > Note: if the final fetchOptions.body is an objet, it will be JSON stringified automatically and the Content-Type will set to "application/json"

  - **httpErrorHandler**: an http error handler function which recieve the request object.

    The reponse object is a simplified plain version of [Response](https://developer.mozilla.org/fr/docs/Web/API/Request):

    ```js
    {
      url: <string>,
      method: <string>,
      headers: <object>,
      body: <string | object>
    }
    ```

    and the response object
    The reponse object is a simplified plain version of [Response](https://developer.mozilla.org/fr/docs/Web/API/Response):

    ```js
    {
      url: <string>,
      status: <number>,
      ok: <boolean>,
      redirected: <boolean>,
      type: <string>,
      headers: <object>,
      body: <string | object> // depend on the parsing
    }
    ```

    By default any error will generate a basic error with the `code` field set to "HTTP_${response.status}"

#### head(path, options)

Performs an HEAD request to the api

##### Parameters

- **path**: the path from the baseUrl
- **options**:
  - **headers**:
    - **[header-name]**: header value
  - **query**: query object
  - **body**: body value, object will be automatically JSON stringified

##### Response

Returns the response body automatically parsed according the response's Content-Type

#### get(path, options)

Performs an GET request to the api

##### Parameters

- **path**: the path from the baseUrl
- **options**:
  - **headers**:
    - **[header-name]**: header value
  - **query**: query object
  - **body**: body value, object will be automatically JSON stringified

##### Response

Returns the response body automatically parsed according the response's Content-Type

#### post(path, options)

Performs an POST request to the api

##### Parameters

- **path**: the path from the baseUrl
- **options**:
  - **headers**:
    - **[header-name]**: header value
  - **query**: query object
  - **body**: body value, object will be automatically JSON stringified

##### Response

Returns the response body automatically parsed according the response's Content-Type

#### put(path, options)

Performs an PUT request to the api

##### Parameters

- **path**: the path from the baseUrl
- **options**:
  - **headers**:
    - **[header-name]**: header value
  - **query**: query object
  - **body**: body value, object will be automatically JSON stringified

##### Response

Returns the response body automatically parsed according the response's Content-Type

#### patch(path, options)

Performs an PATCH request to the api

##### Parameters

- **path**: the path from the baseUrl
- **options**:
  - **headers**:
    - **[header-name]**: header value
  - **query**: query object
  - **body**: body value, object will be automatically JSON stringified

##### Response

Returns the response body automatically parsed according the response's Content-Type

#### delete(path, options)

Performs an DELETE request to the api

##### Parameters

- **path**: the path from the baseUrl
- **options**:
  - **headers**:
    - **[header-name]**: header value
  - **query**: query object
  - **body**: body value, object will be automatically JSON stringified

##### Response*=

Returns the response body automatically parsed according the response's Content-Type

### Running all tests

```sh
$ npm test:all
```

> Note: that's the one you want to use most of the time

### To do

- [ ] improve automatique response parsing, for now buffer are not managed
- [ ] add browser unit tests

## Reporting bugs and contributing

If you want to report a bug or request a feature, please open an issue.
If want to help us improve api-reader, fork and make a pull request.
Please use commit format as described [here](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines).
And don't forget to run `npm run format` before pushing commit.

## Repository

- [https://github.com/sagacify/api-reader](https://github.com/sagacify/api-reader)

## License

The MIT License (MIT)

Copyright (c) 2020 Sagacify

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

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