request-json : simple HTTP client for Node.js to deal with JSON APIs

Most of the web APIs furnishes data formatted with JSON. Even some databases, like CouchDB, propose to manage data through HTTP requests that carry JSON data.

With Node.js, to write an HTTP client that queries these JSON API, there is the famous request library. This one is able to do a lot of stuff but requires a configuration each time you use it with JSON APIs. For instance, if you send a GET request to an URI, you will have to parse returned body or to specify a JSON option. That could be annoying if you do it frequently.

To avoid that I wrote a simple library that extend request and will make your life easier when dealing with JSON API. It is called request-json and is really more straightforward.

Here are some examples, written with coffeescript, it works with Javascript too.

data = title: 'my title', content: 'my content'

# with request uri: 'http://localhost:8888/posts', json: data, (error, response, body) ->
    console.log response.statusCode

# with request-json
client = new Client 'http://localhost:8888/' 'posts/', data, (err, res, body) ->
    console.log response.statusCode

# with request
request.get uri: 'http://localhost:8888/posts', json: true, (error, response, body) ->
    console.log body[0].title

# with request-json
client.get 'posts/', (err, res, body) ->
    console.log body[0].title

request-json brings additional features:

  • keep your base path, dont rewrite it every time.
  • send and save files easily (that’s properly done via streams)
  • add a basic authentication to each of your requests.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: