
Hello, this is the part 1 tutorial on consuming API. We will be consuming the API from a NodeJS application running with Express.
This tutorial assumes that you have an understanding of NodeJS. If you’re new to NodeJS, you can still follow along by following this tutorial on how to setup a NodeJS application on your machine.
The API we will be consuming, is from an application I built for any time I need to try an API call or for tutorials like this, and you can use it too.
The endpoint will be at:
http://jobwater.herokuapp.com/api/jobs
Our Objective
Our objective will be to show the contents of Jobwater in
our NodeJS app. To get the job done we’ll be using request (or request.js)
to handle the http call. Head over to a terminal/command line and cd into the root of
your application folder.
If you followed the tutorial on installing nodejs application, then your folder name should be consumer.
To install request (this will handle our http call to Jobwater), in your terminal/command line =>
npm i request
After request is installed, start your server
nodemon
Your index.js file in the routes folder should look like below:
/consumer/routes/index.js => (if you followed the link above to the tutorial, replace everything in the file with below)
var express = require('express');
var router = express.Router();
var request = require('request');
var url = 'http://jobwater.herokuapp.com/api/jobs';
router.get('/', function(req, res, next){
request.get(url, (error, response, body) => {
let json = JSON.parse(body);
if(error){
res.send(error);
}
res.json(json);
});
});
module.exports = router;
Your server should be running, now head over to the browser and load:
Your browser should appear like the image below (or in raw json format) =>
I'm sure you got it working on your end. For this tutorial, we consumed the API from Jobwater by using a get method, but we're not able to interact with it (no buttons or links).
In the third part of Consuming API, we will be interacting with the API, so I hope you'll be looking forward to it.
About ohiodn8
Ruby on Rails developer, AWS Engineer, anything fun, music, a little bit of mobile game. . .