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
Run the
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) -
We now have a project named
Packages that we need for our hello world app are -
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
You can also checkout the
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(
Quick Explanation of the above code-
Quick Explanation of the above code-
Step 5: Wire-up the installed packages
We have installed 3 packages -
We create a file named
Quick Explanation of the above code-
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
We had coded the response JSON object as
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)t
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.
Adding required dependencies
> npm install --save koa
> npm install --save koa-bodyparser
> npm install --save koa-router
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" }
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;
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 asresponse
and value as'Hello World'
.ctx.body
is assigned the required HTTP response body.ctx.status
is set to200
which implies an OK response.- Lastly, we see that
helloWorldHandler
variable is made visible to outside consumers of this handler usingmodule.exports
. In this case, the consumer will be a custom Hello World router which we will set up in the next step.
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();
const Router = require('koa-router')
creates a newkoa-router
instance.const helloWorldHandler = require('./helloWordHandler')
creates a reference of theHelloWorldHandler
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 invokesHelloWorldHandler
’sgetHelloWorld()
method which contains our API's processing logic. - Lastly, we see that
helloWorldRouter.routes()
is made visible to outside consumers of this router usingmodule.exports
. In this case, the consumer will be theindex.js
file which we see in the next step.
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.');
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 port8080
.
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.
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.
curl
command line utility to invoke our Hello World API as follows - C:\>curl localhost:8080/helloWorld {"response":"Hello World"}
{"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.