Node.js: Build a simple Wikipedia Viewer

Build a command line Wikipedia Viewer that makes an API call.

wiki app on Vscode

So, I built a very simple Wikipedia viewer app that makes a call to the Wikipedia API, and displays the result to the console. Here’s how I achieved it:

Node.js: Download and install node.js, if you haven’t already.

Wikipedai API: This is a free API, no key required. Just read through the documentation and get the required link needed for the API call. This is the link i’ll be using —https://en.wikipedia.org/w/api.php? with some parameters that will enable us perform a search query.

Step 1: Build up the link with the required parameters for search query

Since we basically just want to make an API call that searches Wikipedia and returns the result. We need to use the open Search action which does the following opensearch: Search the wiki using the OpenSearch protocol and with that we can proceed to build up our link with the needed parameters and it should look like this: https://en.wikipedia.org/w/api.php?action=opensearch&search={searchTerm}&format=json

Step 2: Setting up the project

Create a new directory named node-wiki and run npm init , fill out the required information to initialize the project. You can just do the default settings for now, it doesn’t matter. But here’s what my package.json file looks like:

{
“name”: “wiki-app”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1"
},
“author”: “Vanessa Ating”,
“license”: “ISC”,
“dependencies”: {
}
}

3. Create a file named index.js — this is the file that will house all the code for our application.

4. Now, lets make our API call and to do this we need an npm module called request — It is a module that simplifies HTTP request in node. Install request by running: 
npm install request --save

And all we have to do next is, pass in our target URL, and request returns a callback function. Our code should look like this:


var request = require(‘request’);
request(url, function (err, response, body) {
if(err){
var error = “cannot connect to the server”;
console.log(error);
} else {
console.log(‘body:’, body);
}
});

Explaining the code
Require the request package, pass in a URL, and request returns a callback function with three arguments: err, response, and body.

We then check for an error in our request. If there is one, we log the error to the console.and if there is none, we log the entire response of the body to the console.

Back to our link with the required parameters:

https://en.wikipedia.org/w/api.php?action=opensearch&search={searchTerm}&format=json

The URL has three required query parameters. Query parameters are key/value pairs that allow us to pass in data to a URL. And in this URL we need to include the action which we want it to perform(for this case open search) , the search Term (the word we want to search for) and the format we want our response to be in. Here’s what the code will look like:

var query = ‘english’;
var url = `https://en.wikipedia.org/w/api.php?action=opensearch&search="+ ${query} +”&format=json`;

Explaining the code:
Create a variable named query and assign it a string value of the word we’d like to test with, Create a variable named url and assign it the Wikipedia URL with our three required query parameters. Note: Query parameters start with a ? question mark, then indicated with key/value pairs separated by an = equal sign. Different key/value pairs are separated with an & ampersand.

At this point putting everything together our code should look like this:

var request = require(‘request’);
var query = ‘english’;
var url = `https://en.wikipedia.org/w/api.php?action=opensearch&search="+ ${query} +”&format=json`;
request(url, function (err, response, body) {
if(err){
var error = “cannot connect to the server”;
console.log(error);
} else {
console.log(‘body:’, body);
}
});

We can now run our code in the console by typing:

node index.js 
//we get the following back:
body: [“\” english \””,[“English language”,”English Wikipedia”,”English people”,”English Civil War”,”English Channel”,”English literature”,”English Electric Canberra”,”English Football League”,”English as a second or foreign language”,”English Electric Lightning”],[“English is a West Germanic language that was first spoken in early medieval England and is now a global lingua franca.”,”The English Wikipedia is the English-language edition of the free online encyclopedia Wikipedia. Founded on 15 January 2001, it is the first edition of Wikipedia and, as of June 2017, has the most articles of any of the editions.”,”The English are a nation and an ethnic group native to England, who speak the English language. The English identity is of early medieval origin, when they were known in Old English as the Angelcynn (\”family of the Angles\”).”,”The English Civil War (1642\u20131651) was a series of armed conflicts and political machinations between Parliamentarians (\”Roundheads\”) and Royalists (\”Cavaliers\”) over, principally, the manner of England’s government.”,”The English Channel (French: la Manche, \”the Sleeve\”; German: \u00c4rmelkanal, \”Sleeve Channel\”; Breton: Mor Breizh, \”Sea of Brittany\”; Cornish: Mor Bretannek, \”British Sea\”), also called simply the Channel, is the body of water that separates southern England from northern France, and links the southern part of the North Sea to the Atlantic Ocean.”,”This article is focused on English-language literature rather than the literature of England, so that it includes writers from Scotland, Wales, and the whole of Ireland, as well as literature in English from countries of the former British Empire, including the United States.
“,”The English Electric Canberra is a British first-generation jet-powered medium bomber that was manufactured during the 1950s.”,”The English Football League (EFL) is a league competition featuring professional football clubs from England and Wales.”,”English as a second or foreign language is the use of English by speakers with different native languages.”,”The English Electric Lightning is a supersonic fighter aircraft of the Cold War era. It was designed, developed, and manufactured by English Electric, which was subsequently absorbed by the newly formed British
Aircraft Corporation.”],[“https://en.wikipedia.org/wiki/English_language","https://en.wikipedia.org/wiki/English_Wikipedia","https://en.wikipe
dia.org/wiki/English_people”,”https://en.wikipedia.org/wiki/English_Civil_War","https://en.wikipedia.org/wiki/English_Channel","https://en.wiki
pedia.org/wiki/English_literature”,”https://en.wikipedia.org/wiki/English_Electric_Canberra","https://en.wikipedia.org/wiki/English_Football_Le
ague”,”https://en.wikipedia.org/wiki/English_as_a_second_or_foreign_language","https://en.wikipedia.org/wiki/English_Electric_Lightning"]

As you can see, we’ve successfully made a request to Wikipedia’s API and gotten a response back with the above data.

Lets arrange the response in a cleaner way:
The first thing we need to do is convert the response that’s been sent back (called JSON) into a JavaScript Object. (JavaScript Object Notation) is a way to store information in an organized way , that helps accessing data easy and it looks like JavaScript Object. Make the conversion by doing this:

var wiki = JSON.parse(body);

Now we can access the data by dot or bracket notation since it’s an object, but to format it in a much nicer way we need to run a loop. The code should then look like this:

var wiki = JSON.parse(body);
for (var i = 0; i < wiki[1].length; i++) {
var data = `You searched for ${wiki[1][i]}: And these are the details — ${wiki[2][i]} Follow this link to read more — ${wiki[3][i]}` + “\n”;
console.log(data);
}

Running our app now should give us this:

node index.js 
//the response
You searched for English language: And these are the details — English is a West Germanic language that was first spoken in early medieval England and is now a global lingua franca. Follow this link to read more — https://en.wikipedia.org/wiki/English_language
You searched for English Wikipedia: And these are the details — The English Wikipedia is the English-language edition of the free online encyclopedia Wikipedia. Founded on 15 January 2001, it is the first edition of Wikipedia and, as of June 2017, has the most articles of any of the editions. Follow this link to read more —  https://en.wikipedia.org/wiki/English_Wikipedia
You searched for English people: And these are the details — The English are a nation and an ethnic group native to England, who speak the English language. The English identity is of early medieval origin, when they were known in Old English as the Angelcynn (“family of the Angles”).
Follow this link to read more — https://en.wikipedia.org/wiki/English_people
You searched for English Civil War: And these are the details — The English Civil War (1642–1651) was a series of armed conflicts and political machinations between Parliamentarians (“Roundheads”) and Royalists (“Cavaliers”) over, principally, the manner of England’s government. Follow this link to read more —  https://en.wikipedia.org/wiki/English_Civil_War
You searched for English Channel: And these are the details — The English Channel (French: la Manche, “the Sleeve”; German: Ärmelkanal, “Sleeve Channel”; Breton: Mor Breizh, “Sea of Brittany”; Cornish: Mor Bretannek, “British Sea”), also called simply the Channel, is the body of water that separates southern England from northern France, and links the southern part of the North Sea to the Atlantic Ocean. Follow this link to read more - https://en.wikipedia.org/wiki/English_Channel
You searched for English literature: And these are the details — This article is focused on English-language literature rather than the literature of England, so that it includes writers from Scotland, Wales, and the whole of Ireland, as well as literature in English from countries of the former British Empire, including the United States. Follow this link to read more —  https://en.wikipedia.org/wiki/English_literature
You searched for English Electric Canberra: And these are the details — The English Electric Canberra is a British first-generation jet-powered medium bomber that was manufactured during the 1950s. Follow this link to read more —  https://en.wikipedia.org/wiki/English_Electric_Canberra
You searched for English Football League: And these are the details — The English Football League (EFL) is a league competition featuring professional football clubs from England and Wales. Follow this link to read more —  https://en.wikipedia.org/wiki/English_Football_League
You searched for English as a second or foreign language: And these are the details — English as a second or foreign language is the use of English by speakers with different native languages. Follow this link to read more —  https://en.wikipedia.org/wiki/English_as_a_second_or_foreign_language
You searched for English Electric Lightning: And these are the details — The English Electric Lightning is a supersonic fighter aircraft of the Cold War era. It was designed, developed, and manufactured by English Electric, which was subsequently absorbed by the newly formed British Aircraft Corporation. Follow this link to read more —  https://en.wikipedia.org/wiki/English_Electric_Lightning

Now, we can only search for the word English, which isn’t much. Let's make our app be able to search for other words too. And we can do this by installing yargs — It is a CLI tool that enables us define variables from the command line. Install yargs with: 
npm install yargs --save

Yargs works by exposing any variable we use in the console onto the argv object. We can access this object like this:
var argv = require(‘yargs’).argv;

Then set our variable to have a flag q and a default value if nothing is assigned:
var query = argv.q || ‘english’;

Now to run the app we pass in a variable named q like this:

node index.js -q python
//we get a different response

And at this point this is what the final code should look like:

var request = require(‘request’);
var argv = require(‘yargs’).argv;
var query = argv.q || ‘english’;
var url = `https://en.wikipedia.org/w/api.php?action=opensearch&search="+ ${query} +”&format=json`;
request(url, function(err, response, body) {
if (err) {
var error = “cannot connect to the server”;
console.log(error);
} else {
var wiki = JSON.parse(body);
for (var i = 0; i < wiki[1].length; i++) {
var data = `You searched for ${wiki[1][i]}: And these are the details — ${wiki[2][i]} Follow this link to read more — ${wiki[3][i]}` + “\n”;
console.log(data);
}
}
});

I hope this post has been helpful and you enjoyed every bit of it, you can find the full code here

Thanks for reading.