Koa JS
Koa.js is a Node.js web application framework that offers a comprehensive range of functionality for both web and mobile applications. Also, Koajs is open source framework created by the same people that made Express.js.
What is Koa?
Koa provides a simple interface for creating apps. It’s a tiny framework (600 LoC) that includes all of the tools needed to develop apps and is highly adaptable. On npm, there are various modules for Koa that may be immediately inserted into it.
Koa has so many functions called,
- app.callback()
- app.context()
- app.keys =
- app.listen()
- app.use()
- Request & Respons (These two also have so many functions)
Why Koa?
Koa is a very thin layer of abstraction over the node for creating server side apps with a minimal footprint . It has a large community and is totally pluggable. This also allows us to simply extend Koa and tailor it to our own requirements.
Features of Koa
- Designed as a lightweight and flexible framework for Node.js
- Support for ECMAScript 6 (/ES2015) by default
- Developers can use generators as functions to stop and resume the code execution
- Simplifies the use of Error handling by using middleware more effectively
- Identifies and understands all HTTP methods
- Even before Express, Koa had support for
async/await
To begin programming with the Koa framework, you’ll need to install Node and npm (node package management).
Run the following lines in your terminal to verify that node and npm are installed.
$ node --version
$ npm --versionYou should get something like this.
v5.0.0
3.5.2Make sure your node version is more than 6.5.0.
Getting Started
You must first install Koa before you can use it as a server-side framework. Create a directory in which all project-related files will be stored. We’ll start by setting it up as a Node.js project.
# First initialize an empty directory
npm init -yThis will assist us in creating a package.json file that keeps track of all the dependencies we add to our project via npm.
{
"name": "koa-rest-api-tut",
"version": "0.0.1",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Sanduni",
"license": "MIT"
}The next step is to add Koa as a local dependency.
npm install -S koaOur First Koa App
To understand the koa better first we are going to write a Hello World program.
Create a new file called app.js and type the following in it.
// app.js
const Koa = require('koa');
const app = new Koa();
// Our First Route
app.use(async ctx => {
ctx.body = 'Hello World';
});
// Bootstrap the server
app.listen(3000);Then, open your terminal and run the following command:
node app.jsThis will start the server.
Building the REST API
Get Sanduni Jayasinghe’s stories in your inbox
Join Medium for free to get updates from this writer.
The API will not operate until you install dependencies. Let’s get started.
npm i -S koa-body koa-routerkoa-body: body-parser middleware . Supports urlencoded, multi-part and json request bodies. It aids in the creation and response to HTTP POST requests, which may be used as a form field, a file upload, and so on.
koa-router : Routing Middleware that provides ExpressJS style routing using HTTP verbs.
Type the following code in the app.js:
// app.js
const Koa = require('koa');
const koaBody = require('koa-body');
// create app instance
const app = new Koa();
// middleware functions
app.use(koaBody());
// Require the router here
// use the router here
app.listen(3000);Now create a new file and named it as books.js.
// books.jsconst Router = require('koa-router');// Prefix all routes with: /booksconst router = new Router({prefix: '/books'});let books = [{ id: 1011, name: 'Adventures of Sherlock Holmes', author: 'Sir Arthur Conan Doyle' },{ id: 1012, name: 'Oliver Twist', author: 'Charles Dickens' },{ id: 1013, name: 'Frankenstein', author: 'Mary Shelley' },{ id: 1014, name: 'Into The Wild', author: 'John Krakauer' }];// Routes will go heremodule.exports = router;
Let’s build the first route of our API.
Creating a route to handle `GET` request
The code for processing a GET request in Koa is shown below. To books.js, add the following code.
// books.js
router.get('/', (ctx, next) => {
ctx.body = books;
next();
});The callback function attached to the router.get() contains two arguments. Last argument next() is used in the middleware function. This method is called by any middleware function to signal that the current middleware function has been suspended and that the next available middleware function should be used.
When sending the answer, this callback method traverses the books array. To use this, you must first include and call the routes file in app.js.
// app.js
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
// Set up body parsing middleware
app.use(koaBody());
// Require the Router we defined in books.js
let books = require('./books.js');
// Use the Router on the sub route /books
app.use(books.routes());
app.listen(3000);The next step is to run the command: npm run dev and visit the URL http://localhost:3000/books to see the following result.
The next step is to construct a route that would retrieve a book based on its id. Add the following code to the books.js.
// books.js
router.get('/:id', (ctx, next) => {
let getCurrentBook = books.filter(function(book) {
if (book.id == ctx.params.id) {
return true;
}
});
if (getCurrentBook.length) {
ctx.body = getCurrentBook[0];
} else {
ctx.response.status = 404;
ctx.body = 'Book Not Found';
}
next();
});Enter URL as http:localhost:3000/books/1013in your browser window and you will get the following result.
You must deliver an error message with an HTTP status of 404 if the id does not exist or is incorrect.
Handling a POST request
// books.js
router.post('/new', (ctx, next) => {
// Check if any of the data field not empty
if (
!ctx.request.body.id ||
!ctx.request.body.name ||
!ctx.request.body.author
) {
ctx.response.status = 400;
ctx.body = 'Please enter the data';
} else {
let newBook = books.push({
id: ctx.request.body.id,
name: ctx.request.body.name,
author: ctx.request.body.author
});
ctx.response.status = 201;
ctx.body = `New book added with id: ${ctx.request.body.id} & name: ${
ctx.request.body.name
}`;
}
next();
});The /new route is used for creating a new book add it into our books array. The Koa Context object in the above routing middleware examines if any of the data fields required in request.body are present or not. If one of them is missing, the routing middleware will be halted and the user will receive an error message.
If there is no error, this routing moddleware accepts the data and provides a success message with the appropriate HTTP status code for establishing a new record. To run this you can use a REST client such as Postman or Insomnia.
Closing Thoughts
This completes the basics of building a REST API using Koa as a Node.js framework. I will put an additional link here for you to know about the PUT and DELETE methods. Click here to view the web page.
Thank you for taking the time to read; If you enjoyed this article, share it with your friends and colleagues!










