Index
Overview


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

To code an API provider, we're going to leverage our previous routing example. We'll call it the "basic example".

As a matter of fact, we'll only need to make minor tweaks to the basic example.

So we first want to walk through that example and get it working, and then copy the code into this project as a starting point.

Example


Our fundamental change to the basic example is responding with developer-friendly JSON (JavaScript Object Notation) data rather than HTML.

Our serve logic is simpler compared to serving HTML.
serve(results) {
	//serve in JSON format
	const res = this.response;
	res.writeHead(statusCodes.OK, jsonType);
	res.end(JSON.stringify(results));
}
This is a human readable JSON response we are providing to the API consumer (populated with example data).

Our data format here is basically just a JavaScript plain object.

More on JSON....
[{"unit":"m","value":2},
{"unit":"ft","value":6.56168},
{"unit":"mm","value":2000},
{"unit":"cm","value":200},
...]
One other change we'll make to the basic example is adding an API key.

This is a simplified example to show the basic idea -- in reality, we would expand this to support unique keys for each consumer.
authenticate() {
	//check API key
	//simplified authentication to exemplify
	const
		expected = 'Z283794',
		res = this.response;
	if (this.url.query().apiKey !== expected) {
		res.writeHead(statusCodes.BAD_REQUEST, plainType);
		res.end("Invalid API key\n");
		return false;
	}
	return true;
}
If the authenticate fails, we would simply abort the request routing, responding with an error (in this example, "authenticate" will write the error).
processRequest() {
	if (!this.authenticate())
		return;
	this.logRequestInfo();
	this.route();
}
Here is the example project source code.

The project will require an npm init, and then npm install of modules: "http-status-codes" and "url-wrapper".