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

@kth/api-call

v4.1.0

Published

Node.js module to make JSON calls against APIs.

Downloads

3,799

Readme

KTH API Call for Node

Node module used to make JSON calls against APIs. (Previously published as kth-node-api-call, now @kth/api-call.)

To use in your node project, run:

npm i @kth/api-call

Setup

In your init callback to the Express web server, this should happen:

const connections = require('@kth/api-call').Connections

const nodeApi = {
  namedApi: {
    host: 'localhost', // api hostname
    https: false, // use ssl?
    port: 3001, // api port
    proxyBasePath: '/api/applicationName', // api base path
    required: true, // is the api required? Optional, defaults to false
    defaultTimeout: 2000, // milliseconds. Optional, defaults to 2000
  },
}

const cacheConfig = {
  namedApi: {
    redis: {
      host: 'localhost',
      port: 6379,
    },
  },
}

const apiKey = {
  namedApi: '1234',
}

const options = {
  timeout: 5000, // milliseconds, retry interval if getting API-paths fails
  log: myLogger, // your logger instance
  redis: myRedis, // your redis instance
  cache: cacheConfig, // your api cache options
  checkAPIs: true,
}
// either
module.exports = connections.setup(nodeApi, apiKey, options)
// or
const api = connections.setup(nodeApi, apiKey, options)

Note

The checkAPIs option requires that the API implements a checkAPIkey route, see node-api The endpoint can be overridden by setting the statusCheckPath property on the api config object

Usage

Wherever you need to call your api, use something on the form of:

const paths = api.namedApi.paths
const client = api.namedApi.client

// user is a uri parameter
client.getAsync(client.resolve(paths.[YOUR_ENDPOINT], {user: username, etc...}))
.then(response => {
  // do something with result
})

if you want to use a cached api, add the option {useCache: true} to the getAsync call like this:

client.getAsync([FULL_PATH], { useCache: true }).then(response => {
  // etc.
})

BasicAPI

This used to be a straightforward wrapper around request. Since version 4, request is replaced by node-fetch, with efforts made to keep the same methods.

BasicAPI will allow more control but also encourage more code re-use. It allows the use of Promises and caching (via redis) of successful responses (status >= 200 and status < 400).

For more details see the examples below and the source code.

// configure this and re-use throughout your app

const api = new BasicAPI({
  hostname: 'localhost',
  port: 3001,
  json: true,
  https: false,
  headers: {
    api_key: 'abcd',
  },
  // optionally enable redis for response caching
  // redis: {
  //   client: redisClient,
  //   prefix: 'node-api',
  //   expire: 120
  // }
})

// usage example:

const params = { id: 123 }
const uri = api.resolve('/value/:id', params)

// promise
api
  .getAsync(uri)
  .then(response => {
    if (response.statusCode >= 200 && response.statusCode < 400) {
      // do something with response.body
    } else {
      // bad/unexpected status code, delegate error
    }
  })
  .catch(err => {
    // handle/delegate err
  })

// or callback
api.get(uri, (err, response, body) => {
  if (err) {
    // handle/delegate err
    return
  }

  if (response.statusCode >= 200 && response.statusCode < 400) {
    // do something with response.body
  } else {
    // bad/unexpected status code, delegate error
  }
})

HTTP Request Methods

Each of the following sends a corresponding HTTP request. Append Async (e.g. getAsync) to use Promise instead of callback. The first parameter should be either a uri (as a string) or an options object which is passed to node-fetch. For non-async methods the second parameter should be a function with the following signature: function (error, response, body) { ... }. The callback parameters are the same as for the request library.

Note that if you use Redis and/or the async methods you might lose some functionality. For details about this, read the source code!

  • get/getAsync
  • post/postAsync
  • put/putAsync
  • del/delAsync
  • head/headAsync
  • patch/patchAsync

Utility Methods

  • resolve takes two parameters. The first is a uri template, e.g. /value/:name, and the second is a plain object, e.g. { name: 'foo' }. It will then replace :name with the matching values in the object, resolving the uri /value/foo.
  • defaults re-uses the same config and applies another configuration set on top. Basically it does the same as request.defaults() but returns a valid BasicAPI instance.

Migration from version 3 to 4

  • jar and cookie were basic wrappers to the corresponding request methods. They were removed in version 4.
  • defaults was deprecated in version 4. Use new BasicAPI(options) instead.