• Stars
    star
    537
  • Rank 82,649 (Top 2 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

REST API Client Library

Purest

npm-version test-ci-img test-cov-img snyk-vulnerabilities

REST API Client Library

var purest = require('purest')
var google = purest({provider: 'google'})

await google
  .query('youtube')
  .select('channels')
  .where({forUsername: 'GitHub'})
  .auth(token)
  .request()

Table of Contents

This is Purest v4, for older releases take a look at v3 and v2


Introduction

Purest is a tool for building expressive REST API clients

Default Endpoint

Here is a basic configuration for Google:

{
  "google": {
    "default": {
      "origin": "https://www.googleapis.com",
      "path": "{path}",
      "headers": {
        "authorization": "Bearer {auth}"
      }
    }
  }
}

The above configuration can be used to instantiate that provider:

var google = purest({provider: 'google', config})

Then we can request some data from YouTube:

var {res, body} = await google
  .get('youtube/v3/channels')
  .qs({forUsername: 'GitHub'})
  .auth(token)
  .request()

Explicit Endpoint

We can define explicit endpoint for accessing the YouTube API:

{
  "google": {
    "default": {
      "origin": "https://www.googleapis.com",
      "path": "{path}",
      "headers": {
        "authorization": "Bearer {auth}"
      }
    },
    "youtube": {
      "origin": "https://www.googleapis.com",
      "path": "youtube/{version}/{path}",
      "version": "v3",
      "headers": {
        "authorization": "Bearer {auth}"
      }
    }
  }
}

And then request the same data:

var {res, body} = await google('youtube')
  .get('channels')
  .qs({forUsername: 'GitHub'})
  .auth(token)
  .request()

Defaults

Every method in Purest can also be preconfigured with a value:

var google = purest({provider: 'google', config,
  defaults: {auth: token}
})

Then we no longer need to set the access token on each request:

var {res, body} = await google('youtube')
  .get('channels')
  .qs({forUsername: 'GitHub'})
  .request()

Method Aliases

Each method in Purest can have multiple aliases defined for it:

var google = purest({provider: 'google', config,
  defaults: {auth: token},
  methods: {get: ['select'], qs: ['where']}
})

And then use it like this:

var {res, body} = await google('youtube')
  .select('channels')
  .where({forUsername: 'GitHub'})
  .request()

Purest Options

Purest is a flexible tool for abstracting out REST APIs

var google = purest({config: {}, provider: 'google', defaults: {}, methods: {}})
Key Type Description
provider '' Provider name to initialize from the list of providers found in config
config {} Providers configuration to use
defaults {} Any supported configuration option set by default, see below
methods {} List of methods and their aliases to use with this instance

Request Options

Purest is built on top of a powerful HTTP Client

URL Options

Option Description
origin The protocol and domain part of the URL, can contain {subdomain} token
path The path part of the URL, can contain {version}, {path} and {type} tokens
subdomain Subdomain part of the URL to replace in origin
version Version string to replace in path
type Type string to replace in path, typically json or xml

HTTP Methods

All HTTP methods get head post put patch options delete trace connect accept a string to replace the {path} configuration token with, or absolute URL to set the entire url.

Request Options

Option Type Description
method 'string' Request method, implicitly set if one of the above HTTP Methods is used
url 'string' url object Absolute URL, automatically constructed if the URL Options above are being used, or absolute URL is passed to any of the HTTP Methods above
proxy 'string' url object Proxy URL; for HTTPS you have to use tunneling agent instead
qs {object} 'string' URL querystring
headers {object} Request headers
form {object} 'string' application/x-www-form-urlencoded request body
json {object} 'string' JSON encoded request body
multipart {object} [array] multipart/form-data as object or multipart/related as array request body using request-multipart
body 'string' Buffer Stream Raw request body
auth 'string' ['string', 'string'] {user, pass} String or array of strings to replace the {auth} configuration token with, or Basic authorization as object
oauth {object} OAuth 1.0a authorization using request-oauth
encoding 'string' Response body encoding
redirect {object} HTTP redirect configuration
timeout number Request timeout in milliseconds
agent Agent HTTP agent

Response Options

request

  • buffers the response body
  • decompresses gzip and deflate encoded bodies with valid content-encoding header
  • converts the response body to string using utf8 encoding by default
  • tries to parse JSON and querystring encoded bodies with valid content-type header

Returns either String or Object.

buffer

  • buffers the response body
  • decompresses gzip and deflate encoded bodies with valid content-encoding header

Returns Buffer.

stream

Returns the response Stream.

Node Core Options

Any other HTTP request option not explicitly exposed in Purest can be set using any of the response methods:

await google.request({socketPath: ''})
await google.buffer({socketPath: ''})
await google.stream({socketPath: ''})

Endpoint

The explicit endpoint configuration can be accessed in various ways:

// as argument to the Purest instance
await google('youtube')
// using the option name
await google.endpoint('youtube')
// or the default method alias defined for it
await google.query('youtube')

Examples

Purest comes with a fancy logger

npm i --save-dev request-logs
DEBUG=req,res,body,json node examples/file-name.js 'example name'
Category Topic Providers Example
OAuth 2.0 Refresh Access Tokens box google twitch Refresh access tokens
OpenID Connect Verify id_token auth0 google microsoft Discover public keys and verify id_token signature
OAuth 1.0a OAuth 1.0a flickr trello twitter Get user profile
Storage Multipart, Streams box dropbox drive Upload files
Storage HTTP Streams box dropbox Stream file from DropBox to Box

Get access tokens using Grant

More Repositories

1

grant

OAuth Proxy
JavaScript
3,925
star
2

slugify

Slugifies a string
JavaScript
1,346
star
3

express-admin

MySQL, MariaDB, PostgreSQL, SQLite admin for Node.js
JavaScript
1,148
star
4

markdown-viewer

Markdown Viewer / Browser Extension
JavaScript
853
star
5

simplr-smoothscroll

Smooth scrolling in all browsers
HTML
209
star
6

screenshot-capture

Screenshot Capture / Browser Extension
JavaScript
158
star
7

request-compose

Composable HTTP Client
JavaScript
88
star
8

express-admin-examples

Express Admin Examples
JavaScript
74
star
9

stars

GitHub Stars History and Stats
JavaScript
45
star
10

native-messaging

Native Messaging Host Protocol for Browser Extensions
JavaScript
44
star
11

chrome-webstore

Google Chrome Web Store HTTP Client
JavaScript
35
star
12

deep-copy

Deep copy objects and arrays
JavaScript
35
star
13

styler

Styler / Browser Extension
JavaScript
22
star
14

fastify-grant

Fastify plugin for Grant OAuth Proxy
JavaScript
22
star
15

async-harmony

Asynchronous Harmonies
JavaScript
18
star
16

grant-aws

AWS Lambda handler for Grant
HCL
13
star
17

purest-providers

REST API provider configuration for the Purest module
JavaScript
10
star
18

oauth-like-a-boss

Once And For All
JavaScript
9
star
19

grant-profile

User profile middleware for Grant
JavaScript
8
star
20

xsql

SQL Query Builder
JavaScript
8
star
21

markdown-syntax

Markdown Syntax examples for Markdown Viewer
8
star
22

stocktwits

StockTwits API wrapper
JavaScript
7
star
23

recursive-fs

Asynchronous recursive file system operations
JavaScript
7
star
24

grant-vercel

Vercel Serverless Function handler for Grant
Makefile
7
star
25

simov.github.io

My place on the WWW! Oh man!
JavaScript
6
star
26

wallhaven-client

wallhaven.cc HTTP Client
JavaScript
5
star
27

loca

WebKit reporter for Mocha
JavaScript
5
star
28

mysql-validator

MySql data type validation
JavaScript
4
star
29

grant-types

3
star
30

grant-oidc

OpenID Connect middleware for Grant
JavaScript
3
star
31

grant-session

JavaScript
2
star
32

grant-gcloud

Google Cloud Function handler for Grant
HCL
2
star
33

hapi-hogan

Hogan.js templating in Hapi.js
JavaScript
2
star
34

facebook-refresh-token

Refresh Facebook OAuth Access Token
JavaScript
2
star
35

request-oauth

OAuth 1.0a support for request-compose
JavaScript
2
star
36

sr-pagination

Simple pagination generator
JavaScript
2
star
37

riotjs-examples

RiotJS Examples
JavaScript
2
star
38

grant-azure

Azure Function handler for Grant
Makefile
2
star
39

request-logs

HTTP debug logs for request-compose
JavaScript
2
star
40

express-admin-tests

Express Admin Tests
JavaScript
1
star
41

electron-socket

JavaScript
1
star
42

lure

Lure people to your public organization
JavaScript
1
star
43

simplr-fade

jQuery Slider Plugin
JavaScript
1
star
44

request-multipart

Multipart body support for request-compose
JavaScript
1
star
45

slack-incoming-facebook

Slack Incoming WebHook for Facebook
JavaScript
1
star
46

rubinho

RubyGems visualization tool
JavaScript
1
star
47

ansi-webkit

Print ANSI escaped colors in a browser console
JavaScript
1
star
48

matrix

JavaScript
1
star
49

http-headers

Caseless HTTP Headers
JavaScript
1
star
50

passport-stocktwits

Stocktwits authentication strategy for Passport and Node.js
JavaScript
1
star
51

template

Node Module Template
1
star
52

bulk-stream

A stream that emits multiple other streams and chunks one after another
JavaScript
1
star
53

browserside-organic

Organic development in the browser.
JavaScript
1
star
54

http-fetch

HTTP Client for the Browser
JavaScript
1
star
55

markdown-themes

Themes for Markdown Viewer / Browser Extension
CSS
1
star
56

grant-wiki

1
star
57

invites

Public invites for Slack and GitHub
JavaScript
1
star