Index
Overview


A video that accompanies the page is here....

We'll now consume (call) our WEB API.

Note that what we do here will be general -- i.e., we'll be able to apply the pattern to consume other APIs.

Example


The most important thing in calling a WEB API, is the URL.

As shown below we provide the api path or endpoint "/convert/length" and the two params the api provider requires.
http://localhost:3000/convert/length?unit=m&value=2&apiKey=Z283794


We then employ the http module "get" function to call the API and pass along a reader (more on this next).
https
	.get(apiUrl, dataRecr.getReadDataFct())
	.on("error", errorCallback);
We code a class DataReceiver class that is our workhorse.

Keep en eye on the "dataString" ivar, it is where we'll store the API data as we receive it.
class DataReceiver {

constructor(finishFct) {
	this.apiResult = null;
	this.dataString = '';
	this.finishFct = finishFct;
}
Nice simple method right.

This is where it all happens. For each chunk we receive from the API, this method is called and we append it to our ivar.
receiveNextChunk(chunk) {
	//console.log('chunk: ' + chunk);
	this.dataString += chunk;
}
This method is called after we have received all the data from the API.

We use js' global JSON object to parse the string result -- the result of the parse is a friendly plain js object.

We then call the "finishFct" (the one that was provided to us when we were constructed).
finishReceivingData() {
	//console.log('dataString: ' + this.dataString);
	try {
		this.apiResult = JSON.parse(this.dataString);
		this.finishFct(this.apiResult);
	} catch(exception) {
		console.log(`Error calling API: ${this.dataString}`);
		throw exception;
	}
}
Now we do whatever we want with the data -- e.g., do calculations with it, render it onto HTML, etc.

To keep the example simple, here we print the results to the console.
static showApiResult(results) {
	//result is array of pairs {unit, value}
	//if not array, assume we have error
	if (!Array.isArray(results))
		log(results.toString());
	else
		results.forEach(pair => log(`${pair.value} ${pair.unit}`));
}
After running the node app in the normal way, we should see output similar to this.

You will want to startup your API server before running your API consumer

Gotcha - if your editor does not allow you to run multiple web servers simultaneously, then simply start your programs from the console, e.g., "node my-progarm".
-- API Data Received --
2 m
6.56168 ft
2000 mm
200 cm
0.002 km
78.74016 in
0.00124 mi
2.18723 yd
Here is the example project source code.

The project will not require a npm init nor npm install.