How to set up a new Koa 2 App for REST API development on Node.js

Koa 2 has emerged as one of the primary candidate frameworks for developing REST API backends on Node.js. With the arrival of async/await, a feature which is inherently integrated with how Koa 2 works, and the middleware based structure of Koa 2 in which there stacks of functionality relying on the layer below, Koa 2 offers itself as among the primary contender frameworks for developing an API backend on Node.js. In this tutorial, as we build a sample HTTP based GET REST API, we will see in a step-by-step fashion how easy it is to build a REST API ‘engine’ using Koa 2 from the ground up.

Pre-requisites – Please note that tutorial needs Node.js and npm installed.

Step 1: Set up a new Node.js project using npm init
Let’s begin by creating a folder to hold your new Node.js Koa 2 project. In the example below I have created a new folder named jb-koa (short for JavaBrahman-Koa!).

Run the npm init command to create the package.json file, which will contain your project’s information as well as dependencies.

In the example below I have selected all the default options for initializing the new project(by pressing enter for every option without typing any value) –

Creating a new npm project using 'npm init' command
C:\JavaBrahman\WebStormWorkspaces\jb-koa>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (jb-koa)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to C:\JavaBrahman\WebStormWorkspaces\jb-koa\package.json:

{
  "name": "jb-koa",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes)

We now have a project named jb-koa and a package.json file specifying the project information.

Step 2: Installing the required dependencies
In this step we will install all required dependencies, using the standard npm install, that we need for our Hello World Koa 2 app to run.

Packages that we need for our hello world app are –

  • koa – The primary Koa 2 package which contains the Koa 2 framework.
  • koa-bodyparser – Koa 2 body parser package which reads and parses JSON sent as input to the APIs we expose.
  • koa-router – Koa 2 middleware for setting up API routes.

To add the above dependencies, the following commands need to be executed on the command line –

Adding required dependencies
> npm install --save koa
> npm install --save koa-bodyparser
> npm install --save koa-router

To confirm that the required dependencies have been installed, apart from the command line success message you should see for each of the package installs, you can also open the package.json file we created in Step 1 and see the dependencies section. You should see the three dependencies we just added as shown below –

  "dependencies": {
      "koa": "^2.5.2",
      "koa-bodyparser": "^4.2.1",
      "koa-router": "^7.4.0"
  }
You can also checkout the node_modules folder which contains the directories for newly installed packages.
Note – The versions of koa, koa-bodyparser and koa-router may be different for you based on when you install these packages in future.

We now have the project set up and required dependencies installed. It’s now time to start writing code.

Step 3: Writing Hello World API code
Let’s begin writing code by coding a method which contains our hello world logic for returning a simple response. We will write this method in a javascript(.js) file named HelloWorldHandler.js. Handler suffix here indicates the fact that this file ‘handles’ requests sent to the Hello World API. Here’s the code for our handler file which is saved in the main application folder (right next to package.json) –

Writing Hello World API code in HelloWorldHandler.js
//HelloWorldHandler.js
var helloWorldHandler = {
    getHelloWorld: async function (ctx, next) {
        ctx.body = {response: 'Hello World'};
        ctx.status = 200;
        await next();
    }
};
module.exports = helloWorldHandler;
Quick Explanation of the above code-

  • helloWorldHandler is the variable which encapsulates our Hello World handler’s logic.
  • getHelloWorld() is an async method which does the job of sending back the required response for our API – specifically a JSON object with key as response and value as 'Hello World'.
  • ctx.body is assigned the required HTTP response body.
  • ctx.status is set to 200 which implies an OK response.
  • Lastly, we see that helloWorldHandler variable is made visible to outside consumers of this handler using module.exports. In this case, the consumer will be a custom Hello World router which we will set up in the next step.

Step 4: Setting up Hello World API’s Routing Logic
An application can contain many APIs for doing different kinds of jobs. To allow uniquely calling each API, a unique path(or URI) needs to be set up for each API. An instance of a router, created using koa-router, is what will do the required path definition for us. The router, saved in main application folder, will be coded as follows –

Setting up Hello World API's Routing Logic in HelloWorldRouter.js
//HelloWorldRouter.js
const Router = require('koa-router');
const helloWorldHandler = require('./helloWordHandler');

var helloWorldRouter = new Router();

helloWorldRouter.get('/helloworld', async function (ctx, next) {
    await helloWorldHandler.getHelloWorld(ctx, next);
});

module.exports = helloWorldRouter.routes();
Quick Explanation of the above code-

  • const Router = require('koa-router') creates a new koa-router instance.
  • const helloWorldHandler = require('./helloWordHandler') creates a reference of the HelloWorldHandler we created in Step 3.
  • helloWorldRouter.get method is used to define our ‘route’ for the GET API to be invoked.
  • There are 2 parameters for the router’s get() method. First parameter is /helloworld which defines the URI which needs to be invoked to access our API. This URI is relative to the Koa 2 app’s ‘root URI’. The second parameter is an async function which in turn invokes HelloWorldHandler’s getHelloWorld() method which contains our API’s processing logic.
  • Lastly, we see that helloWorldRouter.routes() is made visible to outside consumers of this router using module.exports. In this case, the consumer will be the index.js file which we see in the next step.

Step 5: Wire-up the installed packages
We have installed 3 packages – Koa, Koa-bodyparser and Koa-router. Before we write our Hello World API, we need to wire-up the basic Koa 2 app

We create a file named index.json in the main application folder and write the following code in it –

Wiring up the Koa 2 app in index.js
//index.js
const Koa = require('koa');
const app = new Koa();

const KoaBodyParser = require('koa-bodyparser');
app.use(KoaBodyParser());

app.use(require('./helloWorldRouter'));

app.listen(8080);

console.log('Hello World Koa app started and listening on port 8080.');
Quick Explanation of the above code-

  • const Koa = require('koa') creates a reference to the Koa 2 module.
  • const app = new Koa() creates an instance of a new Koa 2 app.
  • const KoaBodyParser = require('koa-bodyparser') creates a reference to the koa-bodyparser module.
  • app.use(KoaBodyParser()) sets up an instance of koa-bodyparser to be used for parsing bodies of incoming requests.
  • app.use(require('./helloWorldRouter')) wires up helloWorldRouter instance we defined in HelloWorldRouter.js as a routing middleware.
  • app.listen(8080) creates a Koa 2 server instance running on port 8080.

Now that our Koa app instance is ready to get started and start processing incoming requests using Koa-Router and Koa-BodyParser module, lets now start the server and see our API in action.

Step 6: Starting the server
We will use the standard node command to start the app as follows, i.e. ‘node index.js‘ –

C:\JavaBrahman\WebStormWorkspaces\jb-koa>node index.js
Hello World Koa app started and listening on port 8080.
The second line in above box tells us that Koa 2 app has been started.

Now we are done with the code part(Steps 1 to 5) and server is started with our Hello World GET API deployed on it. Now we need to test the API and see that it returns the response we coded in HelloWorldHandler.js.

Step 7: Invoking the API
We will use the curl command line utility to invoke our Hello World API as follows –

C:\>curl localhost:8080/helloWorld
{“response”:”Hello World”}

We had coded the response JSON object as {"response":"Hello World"} and that is what we have received as output.

Summary
In this tutorial we looked at how to setup a Koa 2 app from scratch. We coded all the layers for the app consisting of the entry point(index.js), router(HelloWorldRouter.js) and handler(HelloWorldHandler.js) to setup a HTTP GET Hello World API. Finally, we invoked the API and saw that it worked as expected.

Digiprove sealCopyright © 2014-2018 JavaBrahman.com, all rights reserved.