Utility for creating REST API wrappers with minimal configuration.
npm install api-wrapperThe returned wrapper uses the request module to make HTTP calls.
Specify the root URL for the wrapped API with the root option.
Create functions on the wrapper by passing a map of function names to path patterns for each HTTP METHOD.
``
ApiWrapper = require('api-wrapper');
mjpClient = ApiWrapper.create({
root: 'https://michaeljperri.com/api/',
parseJson: true,
get: {
search: '/search/${zipCode}?radius|make'
getCustomerById: '/search/${customerId}'
},
post: {
postMessage: '/message/${messageId}'
},
requestDefaults: {
headers: { 'auth-token': 1337 }
}
});
`
Now you can call the wrapped API like this:
`
mjpClient.search({ zipCode: 11746, radius: 30, make: 'Ford' }, callback);
// makes a GET request to https://michaeljperri.com/api/search/11746?radius=30&make=Ford
mjpClient.postMessage({ messageId: 1234 }, 'some-post-data', callback);
// makes a POST request to https://michaeljperri.com/api/submit/1234 with the body 'some-post-data'
function callback(error, message, body) {
if (!error) {
console.log('Got response:', body);
} else {
console.warn('Got error:', e);
}
}
`
${pathVariable}`) or query params (separated by pipes like `?param1|param2|param3`).$3
If true, the wrapper will attempt to parse the response body as JSON before passing it to the callback.$3
The requestDefaults parameter will be passed to request.defaults.$3
You may need to set more options for the request module, for example, HTTP headers.You can set options for all calls to an endpoint when creating the wrapper:
`
ApiWrapper = require('api-wrapper');mjpClient = ApiWrapper.create({
root: 'https://michaeljperri.com/api/',
post: {
postMessage: '/message/${messageId}',
submit: {
pathPattern: '/submit/${formId}',
requestOptions: {
headers: [
{
name: 'content-type',
value: 'application/x-www-form-urlencoded'
}
]
}
}
}
});
`Now calling mjpClient.submit({}, 'request-body', callback) will make a request with the given headers.
You can also add more options to the request object when you call the function by adding another parameter before the callback, e.g.:
`
mjpClient.submit({}, 'request-body', { headers: { 'cookies': 'someCookie=blah;' } }, callback)`For a request that doesn't take a body parameter, that would be:
`
mjpClient.search({}, { headers: { 'cookies': 'someCookie=blah;' } }, callback)
`See the request documentation for the full list of options.
Promisify
If you prefer to use promises rather than callbacks, the returned wrapper can be 'promisified' with Bluebird.`
var Promise = require('bluebird');mjpClient = Promise.promisifyAll(mjpClient);
mjpClient.searchAsync({ formId: 1234 }, 'some-form-data')
.then(function (message, body) {
console.log('Got response:', body);
})
.catch(function (e) {
console.warn('Got error:', e);
});
``See the bluebird documentation for more details.