Request Library

Published at: April 4, 2019, 5:42 a.m. in the Documentation

For convenient requests, we made the Request library and added it to our smappi-cl.
The library by default performs synchronous requests, which significantly differs from competitors.
This improves the readability of your API functions.

Features

Supports GET, POST, PUT and DELETE methods.
You can transfer data, options (e.g. encoding, strategy for processing redirects, etc.) and any custom headers.
Supports work with Smappi Proxy.
It is possible to select the User Agent (it will soon be possible to select the desired one by the filter).

The request looks like this:

request.get(URL, {...GetParams}, {...options}, {...headers});
request.post(URL, {...PostData}, {...options}, {...headers});

Returns a Response object that contains the following properties and methods:

  • url - final URL (after all redirects)
  • status - web server status code
  • headers - web server response headers
  • content - web server response content
  • json() - if the server gave JSON, then you can call this method and get the immediately parsed JavaScript object

Simple request example

const { request } = require('smappi-cl');

function example () {
    return request.get(url).json();
}

module.exports = { example };

Sending data

Send GET data:

request.get(url, {key1: 'value1', key2: 'value2'});

Send POST data:

request.post(url, {key1: 'value1', key2: 'value2'});

File transfer and encoding option

To send a file, specify the option "encoding: null", otherwise the library will encode to "utf8":

request.post(url, {content}, {encoding: null});

followLocation option

By default, upon receiving a 301/302 redirect, the Request will follow the "location".
This behavior can be disabled:

request.get(url, {}, {followLocation: false});

Work with a proxy

Request library supports proxy.
To do this, it is enough to call the withProxy method in the call chain, with the optional condition parameter:

function condition (resp) {
    return resp.status == 200;
}

request.withProxy(condition)
    .get('https://proxy.smappi.org/check')
    .json();

You can read more about the work of proxies in the article How to use Proxy Service.