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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...