request-json : simple HTTP client for Node.js to deal with JSON APIs
2012/12/06 Leave a comment
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.
data = title: 'my title', content: 'my content' # with request request.post uri: 'http://localhost:8888/posts', json: data, (error, response, body) -> console.log response.statusCode # with request-json client = new Client 'http://localhost:8888/' client.post '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.title # with request-json client.get 'posts/', (err, res, body) -> console.log body.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.