How to Consume a RESTful API Like a Boss Using Node.js

What is RESTful API

  • Resource
  • Endpoint
  • HTTP Methods/Verbs

What Are HTTP Methods

1. GET

GET http://www.example.com/users

GET http://www.example.com/users/89

2. POST

POST http://www.example.com/users

3. PUT

PUT http://www.example.com/users/89

4. PATCH

PATCH http://www.example.com/users/89

5. DELETE

DELETE http://www.example.com/users/89

6. What Is The Difference Between PUT And PATCH

Let’s Get Practical

What We’ll Be Building

Demo Teams List
mkdir serie-a-standings
cd serie-a-standings
touch package.json
subl .
// package.json

{
"name": "serie-a-standings",
"description": "A sample app that demonstrates how to consume football-data RESTful API",
"main": "server.js",
"dependencies": {
"handlebars": "^4.0.6",
"hapi": "^16.0.2",
"lodash.filter": "^4.6.0",
"lodash.take": "^4.1.1",
"request": "^2.79.0",
"vision": "^4.1.1"
}
}

Project Dependencies

  • Hapi: this is obvious since our app is built on Hapi.js.
  • Vision: a Hapi.js plugin that allow for views in Hapi.js application.
  • Handlebars: project’s templating engine.
  • Request: HTTP request client for Node.js.
  • Lodash.filter: Lodash collection filter method.
  • Lodash.take: Lodash Array take method.
npm install
// server.js

'use strict'

const Hapi = require('hapi');
const Request = require('request');
const Vision = require('vision');
const Handlebars = require('handlebars');
const LodashFilter = require('lodash.filter');
const LodashTake = require('lodash.take');

const server = new Hapi.Server();

server.connection({
host: '127.0.0.1',
port: 3000
});

// Register vision for our views
server.register(Vision, (err) => {
server.views({
engines: {
html: Handlebars
},
relativeTo: __dirname,
path: './views',
});
});

server.start((err) => {
if (err) {
throw err;
}

console.log(`Server running at: ${server.info.uri}`);
});
// server.js

// Show teams standings
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
Request.get('http://api.football-data.org/v1/competitions/438/leagueTable', function (error, response, body) {
if (error) {
throw error;
}

const data = JSON.parse(body);
reply.view('index', { result: data });
});
}
});

// A simple helper function that extracts team ID from team URL
Handlebars.registerHelper('teamID', function (teamUrl) {
return teamUrl.slice(38);
});
// views/index.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

<title>Serie A Standings | A sample app that demonstrate how to consume football-data RESTful API</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.2.3/css/bulma.min.css">
</head>
<body>

<div class="container">
<div class="section columns">
<div class="column is-8 is-offset-2">
<h2 class="title has-text-centered">
{{ result.leagueCaption }}
</h2>

<table class="table is-bordered is-striped is-narrow">
<thead>
<tr>
<th width="10px">#</th>
<th>Team</th>
<th>P</th>
<th>W</th>
<th>D</th>
<th>L</th>
<th>F</th>
<th>A</th>
<th>GD</th>
<th>Pts</th>
</tr>
</thead>
<tbody>
{{#each result.standing}}
<tr>
<td>{{ position }}</td>
<td>
<a href="teams/{{teamID _links.team.href }}">
{{ teamName }}
</a>
</td>
<td>
{{ playedGames }}
</td>
<td>
{{ wins }}
</td>
<td>
{{ draws }}
</td>
<td>
{{ losses }}
</td>
<td>
{{ goals }}
</td>
<td>
{{ goalsAgainst }}
</td>
<td>
{{ goalDifference }}
</td>
<td>
{{ points }}
</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
</div>
</div>

</body>
</html>
node server.js
Demo Teams List
// server.js

// Show a particular team
server.route({
method: 'GET',
path: '/teams/{id}',
handler: function (request, reply) {
const teamID = encodeURIComponent(request.params.id);

Request.get(`http://api.football-data.org/v1/teams/${teamID}`, function (error, response, body) {
if (error) {
throw error;
}

const result = JSON.parse(body);

Request.get(`http://api.football-data.org/v1/teams/${teamID}/fixtures`, function (error, response, body) {
if (error) {
throw error;
}

const fixtures = LodashTake(LodashFilter(JSON.parse(body).fixtures, function (match) {
return match.status === 'SCHEDULED';
}), 5);

reply.view('team', { result: result, fixtures: fixtures });
});
});
}
});
// views/teams.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

<title>{{ result.name }}</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.2.3/css/bulma.min.css">

<style>
li {
list-style: none;
}
</style>
</head>
<body>

<div class="container">
<div class="section columns">
<div class="column is-8 is-offset-2">
<h2 class="title has-text-centered">
{{ result.name }}
</h2>

<div class="box">
<article class="media">
<div class="media-left">
<figure class="image is-64x64">
<img src="{{ result.crestUrl }}" alt="Team Logo">
</figure>
</div>
<div class="media-content">
<div class="content">
<aside class="menu">
<p class="menu-label">Basic Information</p>

<ul class="menu-list">
<li>
<strong>Name:</strong> {{ result.name }}
</li>
<li>
<strong>Code:</strong> {{ result.code }}
</li>
<li>
<strong>Short Name:</strong> {{ result.shortName }}
</li>
<li>
<strong>Square Market Value:</strong> {{ result.squadMarketValue }}
</li>
</ul>
</aside>
</div>
</div>
<div class="media-right">
<a href="/" class="button">Home</a>
</div>
</article>
</div>

<div class="box">
<h2 class="title has-text-centered">Fixtures</h2>

<div class="content has-text-centered">
<ul>
{{#each fixtures}}
<li>
<strong>{{ homeTeamName }}</strong>
vs
<strong>{{ awayTeamName }}</strong>
</li>
{{/each}}
</ul>
</div>

</div>
</div>
</div>
</div>

</body>
</html>
Demo Team Details

Conclusion

EloquentWebApp Logo

Subscribe Now for Exclusive Content

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store