Skip to main content

Build a command line Node.js app that consumes a REST API

Node.js, a Javascript runtime, along with its frameworks, Express,Sails and the HTTP core module has come to be famously used for creating and deploying servers. In this article we will be making http requests and working with the response in our node apps rather than handling and responding to them as is the common use.

The article assumes the reader is familiar with the already used web terminologies,has node installed and by now realises we wont be doing any actual eating.

If you would prefer a you tube video on the same topic ,please use this link to watch

Background

We will be building a CL(command line) app that takes user input,which will be a country name,using a flag argument and uses this argument to make a http request to a REST API,the api we will be using is provided by restcountries.eu .The api provides information on a country as requested using a parameter.We would consume this API to get the population of a country.

To parse CL arguments we will use Yargs,a node package. To make http requests we will use Axios . Axios is a http client for the browser and node js ,similar to the Fetch API. Lets get to it.

Setting up the Node application

To set up the node application, navigate to your project folder and enter the following command in your CL to initialise the node app:

$ npm init

A couple of questions will follow as prompts. We won’t concentrate on those but please answer as you see fit or keep pressing the enter key to use all default responses. The prompts help generate the package.json,the package.json is a file that contains various metadata for the project.

You should now have a file named package.json in your folder. The content should be similar to this(not to the detail):

package.json

Install dependencies

Install the dependencies needed,yargs and axios. Run the command :

$ npm install yargs axios --save

We are now ready to write the application logic.

Writing app logic

create a file named app.js where we would be writing the application logic :

$ touch app.js

import the dependencies :

//import the dependencies using require
const yargs = require('yargs');
const axios = require('axios').default;


Enter Yargs

Yargs is a node package that helps build command line tools by parsing command line arguments.

We will be using the argument from the country flag(sic) as the input. Get the argv property from the yargs object imported and assign to a variable:

//import the dependencies using require
const yargs = require('yargs');
const axios = require('axios').default;


let argv = yargs.argv
let country = argv.country;
console.log(country)


when we run the node command in other to start our app,any other extra argument,in this case country, would be appended as a property to the argv object.

Run the following command to see the current result from the app:

$ node app.js --country=nigeria

You should see the country being displayed in the console.Now we need to use this value to make a http request.

Enter Axios

Axios is a http client that allows for the use of promise syntax and that is what we will use. we will work with the endpoint from restcountries.eu that allows for the use of name as parameter;

https://restcountries.eu/rest/v2/name/{name}

write an if statement to only make http request when country variable is defined:


const yargs = require('yargs');
const axios = require('axios').default;

let argv = yargs.argv
let country = argv.country;


if(country){
    let url = `https://restcountries.eu/rest/v2/name/${country}`
}
else{
    console.log('Please enter a country')
}

 is able to make requests using all http methods; GET,POST,PUT e.t.c are all allowed. we will use the get method but if you wish to explore others,the official axios documentation is available here

Write code to make http request :

const yargs = require('yargs');
const axios = require('axios').default;

let argv = yargs.argv
let country = argv.country;


if(country){
    let url = `https://restcountries.eu/rest/v2/name/${country}`
axios.get(url,{
    
})
.then((response) => {
    let country = response.data[0];
    console.log('Population:',country.population);
})
.catch(err => {
    console.log(err);
})
}
else{
    console.log('Please enter a country')
}


Axios resolves the response from the http request and rejects in case of an error. In our then statement we get the data property of the response object.The data property is actually what is returned in the api response body.The API returns an array as the data,we will always use the first element of the array . The elements in the array are objects containing information of the country specified as a parameter in the url i.e the one passed as an argument.

Note that in other to keep things simple,we did not check response status or handle any other possible outcomes apart from a 200 OK

Finally,We log the population which is a property of the element to the console.We also write an else statement where we log a prompt to the user to add a country argument.

Run the final app

After coming this far,all that is left is to run and test our app. Run the command to test that the app shows a message when no country argument is entered :

$ node app.js 

The response should be:

$ Please enter a country

Awesome! Now for the final moment,Run the app with the country flag and argument :

$ node app.js --country=brazil

Response should be,wait for it…

$ Population: 206135893






























Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...