Consuming external APIs from Node.js
There will undoubtedly be a time when you want to consume an API directly from within your Node.js code. Perhaps your own API endpoint needs to first fetch data from some other, unrelated third-party API before sending a response. Whatever the reason, the act of sending a request to an external API endpoint and receiving a response can be done fairly easily by using a popular and well-known npm
module called request
. The request
module was written by Mikeal Rogers and is currently the third most popular (and most relied upon) npm
module, after async
and underscore
.
Request is basically a super simple HTTP client, so everything you've been doing with Postman REST Client so far is basically what Request
can do, only the resulting data is available to you in your Node code, as well as the response status codes and/or errors, if any.
Consuming an API endpoint using request
Let's do a neat trick and actually consume our own endpoint as if it was some third-party...