Simple REST Server using KOA 2.0

Koa is a web framework for Node.js. With the release of KOA 2.0, we can now use ES2017’s async functions to express our middleware with KOA. KOA does not come bundled with any middleware, but quite a few packages are available in npm.


Requirements

We need to have node version of 7.6.0 or greater. You can use the node version manager n to update node to a suitable version for KOA.

$ n 7.6.0

Installation

First, let us create a directory for the project.

$ mkdir testApp

Next, let us initialize this project with a package.json file by running

$ cd testApp
$ npm init

We can install KOA using the node package manager. We will make use of the koa-mount and koa-router middleware packages as well.

 $ npm install koa koa-mount koa-router --save

Structure

Next, let us create the following project structure

testApp
|______router
| |______car.js
|______server.js
|______package.json

Server

In the server.js file, we will first need to require the packages.

const Koa = require('koa');
const router = require('koa-router')();
const mount = require('koa-mount');

Next, we need to create an instance of the Koa object and then mount our router files.

const app = new Koa();
app.use(mount(require('./router/car.js')));

We then need to listen to a port for the app to run on.

if(require.main === module) {
app.listen(3000); // default
}

Putting them all together, our server.js file will look like this.

// require packages
const Koa = require('koa');
const router = require('koa-router')();
const mount = require('koa-mount');
// create an instance of the Koa object
const app = new Koa();
// mount the route
app.use(mount(require('/router/car.js')));
if(require.main === module) {
app.listen(3000); // default
}

Routes

In the route directory, let us create our API’s endpoints. We can do this by creating another KOA object and exporting it as a mini server by itself.

In car.js,

const Koa = require('koa');
const router = require('koa-router')();
const app = new Koa();
// a simple car object that we can serve
const car = {
make: 'Honda'
year: '2012'
model: 'Civic'
};

Let us then create an endpoint that can serve our car object for a GET request.

router.get('/car', async (ctx, next) => {
ctx.body = car;
await next();
});

We then need to export our mini server so that it can run on port 3000.

Our car.js will then look like,

const Koa = require('koa');
const router = require('koa-router')();
const app = new Koa();
// a simple car object that we can serve
const car = {
make: 'Honda'
year: '2012'
model: 'Civic'
};
// Route to handle GET request
router.get('/car', async (ctx, next) => {
ctx.body = car;
await next();
});
module.exports = app;

That’s it!!

This way we can keep our backend API organized and simple using KOA 2.0.

Sources:

KOAjs, koa-router, koa-mount

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.