npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

rest-api-handler

v2.22.18

Published

Handler for REST APIs

Downloads

1,066

Readme

REST API Handler

npm version renovate-app Known Vulnerabilities codecov travis

This library will help you with requests to REST APIs. It uses Fetch API which isn't supported by node and some older browsers and Node. Remember to include polyfill if need it.

Basic request

Install npm library:

npm install rest-api-handler --save

First initiate Api class and then you can send HTTP requests. As first parameter use base url.

import { Api } from 'rest-api-handler';

const api = new Api('https://api.blockcypher.com');

api.get('v1/btc/main').then((response) => {
    console.log(response); // same response as in Fetch API
});

// or you can request full url

api.get('https://api.blockcypher.com/v1/btc/main');

In default configuration, response is same as in Fetch API. That why you can define your own processors that will parse responses or use default one provided by this library.

import { Api, defaultResponseProcessor, DefaultApiException } from 'rest-api-handler';

const api = new Api('https://api.blockcypher.com', [
    new DefaultResponseProcessor(DefaultApiException),
]);

api.get('v1/btc/main').then((response) => {
    console.log(response.code); // 200
    console.log(response.data); // parsed JSON
    console.log(response.source); // original Response
});

Here is how to create your own response processors and use them in the chain:

const api = new Api('//some.api.com', [
    new DefaultResponseProcessor(DefaultApiException),
    onlyDataProcessor,
]);

function onlyDataProcessor(response) {
    return Promise.resolve(response.data);
}

api.get('endpoint').then((response) => {
    console.log(response); // parsed JSON
});

Methods

There are default methods for GET, POST, PUT and DELETE. But you can send any HTTP method using request.

api.get('v1/btc/main'); // GET https://api.blockcypher.com/v1/btc/main
api.get('v1/btc/main', { a: 'b' }); // GET https://api.blockcypher.com/v1/btc/main?a=b

api.post('method', { a: 'b' });
api.put('method', { a: 'b' });
api.delete('method');

// you can create your own requests
// use can use other parameters from Fetch API - https://developer.mozilla.org/en-US/docs/Web/API/Request
api.request('endpoint', 'PUT', {
    body: 'Simple string request',
});

Data encoding

By default, data for POST and PUT are encoded as JSON. You can also encode them as FormData. This can be used for images or files uploading.

import { Api } from 'rest-api-handler';
const api = new Api('//some.api.com');

api.post('file-upload', {
    file: fileObject,
}, Api.FORMATS.FORM_DATA);

Authentication

You can authorize to API by using default headers or set them after.

const api = new Api('//some.api.com', [], {
    Authorization: 'Bearer XYZ',
    'Content-Type': 'application/json',
});

// this will replace original default value
api.addDefaultHeader('Authorization', 'Bearer ABC');

// this will delete authorization
api.removeDefaultHeader('Authorization');

You can also set custom headers for every request:

api.request('endpoint', 'GET', {}, {
    'Authorization': 'Bearer XYZ',
})

Node

To use it as node library, just import Fetch polyfill:

require('cross-fetch/polyfill');
const FormData = require('form-data');

global.FormData = FormData;

const { Api, DefaultResponseProcessor, DefaultApiException } = require('rest-api-handler');

const api = new Api('https://api.blockcypher.com', [ new DefaultResponseProcessor(DefaultApiException), ]);

api.get('v1/btc/main').then((response) => {
    console.log(response.data);
});

Exception handling

When you catch exception from fetch it might be tricky. It can be response from api or some javascript syntax error. You can create exception throwing. Use example or your own methods:

import { Api, DefaultResponseProcessor, DefaultApiException } from 'rest-api-handler';

const api = new Api(apiUrl, [
    new DefaultResponseProcessor(DefaultApiException),
]);

api
    .get('some-namespace')
    .catch((exception) => {
        if (exception instanceof DefaultApiException) {
            console.log('Api throwed some exception. Do something.');
        };
        console.log('There was some other exception');
        throw exception;
    });