Skip to content

Instantly share code, notes, and snippets.

@amandeepmittal
Created Oct 4, 2018
Embed
What would you like to do?

Building a REST API with Koa

There are quite a few Node.js frameworks available for web development to build a back-end server for a web or a mobile application. The most popular one is ExpressJS which is being used throughout the industry for a long time. You may already know that if you are using Node.js. In this article, however, we are going to discuss Koa, to write server-side code that too uses Node.js as the runtime engine. We will build a small REST API to demonstrate the use case and then test it using a REST Client.

What is Koa?

Koa is designed and built by the team behind ExpressJS with additions such as promises and async/await support in its core. These ES2015 features are used to tackle API's asynchronous calls. Distributed as a lightweight Node.js framework, Koa provides a minimal interface for developing web applications and APIs. It has features that help JavaScript developers who want to use and leverage Node.js to accelerate the development of APIs and web applications. I have been using Koa for some of my latest back-end applications and I would love to share my knowledge to get you started.

Features of Koa

Some of the features that this framework possesses are:

  • 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 use this framework, the only two requirements you are going to need to run the code examples below is to have Node.js installed in your local machine along with npm to access and install it as a dependency. Another requirement is to have an understanding of JavaScript as a programming language.

Getting Started

To start using Koa as a server-side framework you will have to install it first. Create a directory where you will want to place all the project related files. We will first initialize it as a Node.js project.

https://gist.github.com/de28cea3e88fc9d27482b1ead747dd77

This will help us generate a package.json file that further holds all the record of dependencies we add to our project using npm. I am using -y flag to skip the questionnaire prompted by npm. You will get a similar result once it is done.

https://gist.github.com/fd4401d3e7b76a4ce4c687092b73138a

Next step is to add Koa as a local dependency. I am sure you know what a local dependency here means. If not, please refer to npm documentation.

https://gist.github.com/734bf6be97d43608ce8b3a8d424c45e9

So far so good. Now we can get started and build our application. However, please note that to use Koa either on your local machine or deploy any server-side project that uses it, you need to have Node.js version equal to or greater than v7.6.0.

Our First Koa App

To understand it better and point out the differences with a commonly used framework such as ExpressJS, we are going to write an obligatory Hello World program first. Below, we create a route in a file called app.js.

https://gist.github.com/e99976a0ae3163d31b2ea39f9fd7cb1d

Now, open the terminal and run the following command:

https://gist.github.com/34740af62dc1ff8e52f08d761a08534f

If you are not prompted with an error, that means the server runs successfully. Right now, we are not getting anything exciting from the terminal. If you go to http://localhost:3000 in your browser window, you should see a Hello World message greeting you!

koa-1

To understand more what is happening, we start by importing Koa library into our app.js file. Next, we define an instance called app that will access all the methods that are included in Koa's API such as use() and listen(). app.use() is how define middleware function. We are using this middleware function as a route. The app.listen() is how the server knows to run on a port number specified such as 3000.

Wait, What is ctx?

Another important feature that we use in our bare minimum example is ctx. I do hope you noticed it there. We are using it as an argument to the asynchronous middleware function. It is called Context in Koa and it encapsulates request and response objects into a single object. Unlike ExpressJS, that requires request and response as separate objects passed as arguments. For example:

https://gist.github.com/c8f890c7137f5a9a8cdcc7720975a1f3

In Koa, a context is created per request that comes to the server and is always referenced as a middleware.

https://gist.github.com/141965cdd899ee6591246082b00a8657

Side Tip: Installing nodemon

Before I start on REST APIs, the core of the article, I want to introduce a great tip that is helpful in building a Node.js application. During the development mode, irrespective of the framework I am using, I use nodemon as a dependency to watch for file changes and automatically restart the application. This eliminates the need of running node [filename].js command again and again. You can totally, skip this step and move on the next one where I show the steps for writing the REST API.

This small utility has such an impact on my workflow that it saves hours of development chores. So let me show you how to set it up in our demo application. I will be using the same project as previous Hello World example. Write the following command to install it.

https://gist.github.com/5eeb0d77fc12ca17494fbcc4c1e848d4

-D flag is used to tell npm to install the current dependency as a devDependency. The difference between it and a normal dependency is that devDependencies tend to work only in development environment. They are not installed in a production environment since there is no use of them there. Other types of devDependencies you might come across when writing Node applications are linting tools such as ESLint.

Once, nodemon is installed, append the package.json file and an npm script.

https://gist.github.com/73ec76bb4dfb30fb9ff7520d57a43850

Point this script to the initial file of the Koa application, in our case, it is app.js. To run the application now, all you have to type is npm run dev command in your terminal. This time, you will see a few messages suddenly prompted in the terminal. These messages are provided by nodemon.

Building the REST API

Finally, you have arrived at the point where you can start building the REST API. You have to install dependencies for the API to work. Lets install them.

https://gist.github.com/6b46efd44e83f0bf6c50ab27f93587fc

What are these dependencies for?

koa-body is a body-parser middleware. It supports urlencoded, multi-part and json request bodies. Basically, it helps to create and respond to HTTP POST requests which are available as a form field, or a file upload, etc. It tells the server that the incoming request from the client has a body of data. ExpressJS uses the same approach in handling body requests.

koa-router is the routing middleware that provides ExpressJS style routing using HTTP verbs. It has methods that you can directly use in the application Such as app.get(), app.post(), etc.

Note: I will be mocking data in this application for the sake of brevity and clear understanding of framework's concepts. If you want to, you can use the database of your choice. The structure of data is not complex.

Write the following code in the app.js file.

https://gist.github.com/04b0542c8532068a0bd40e9838f3448c

After body-parser middleware, you are going to have the routes. I am using another file to describe the routes to separate the code for clear understanding. Create a new file called books.js. Define the following inside that file with the data to mock.

https://gist.github.com/a42da174f381bfa403c295bebf2dbc77

First, I am importing the necessary dependency to create routes: koa-router. The next step is to create an instance of this newly imported dependency. Notice the prefix part: /books. Using a prefix for the routes is how you can define and categorized different routes. You can also use this technique to classify the different API versions such as v1, v2, etc.

The books array is the mock data. It contains information about books and each book is represented by a separate object inside the array. Each object further has three data fields: id, name, and author.

Let's build the first route of our API.

Creating a GET request

Below is the code for creating a GET route in Koa. Add the following code to books.js.

https://gist.github.com/354764ce887ed630fbee708192bb2ba0

The callback function attached to the router.get() contains two arguments. I have already explained to you what ctx or context is. The last argument is next(). This is often used in middleware functions. Any middleware function invokes this function to indicate the current middleware function has suspended running and the next middleware function available must be invoked.

This callback function traverses through the books array when to send the response. To run this, you have to first include the routes file in app.js and invoke them.

https://gist.github.com/afbbdbed1015f1649ecd74c4dcae2c71

Next step is to run the command: npm run dev and visit the url http://localhost:3000/books to see the following result.

![koa-2]

Congratulations! 🎉 You just build your first route using Koa. Next step is to create a route to fetch a book by its id. It is going to use the similar approach as the previous route, plus we see how to extract information from request.params object of an incoming request.

https://gist.github.com/3da6f1d46d60b13f02c505b2132d4a3e

Routing parameters are named segments that are used capture the values specified in the URL. In our case, such as:id. Above, we define a routing middleware function that can handle incoming requests from URLs such as http:localhost:3000/books/103. Enter this URL in your browser window and you will get the following result.

![koa-3]

In case of when id does not exist or is invalid, you have to send an error message with an HTTP status of 404.

~[koa-4]

Handling a POST request

The last route you are going to build for this demonstration is going to handle POST requests.

https://gist.github.com/ba0bd6dd80d4950f8a7e3c272687bd68

The /new route is used for creating a new book add it into our books array. I am using this to mock data and not real database so restarting the application will delete the newly added books. In the above routing middleware, the Koa Context object first checks if any of the data field required in request.body is present or not. If one of them is missing, this routing middleware will be terminated then and sends back an error to the user.

If everything is fine, this routing middleware accepts the data and returns success message with correct HTTP status of code for creating a new record. To run this URL, I am using curl command from my terminal but you can use any REST client such as Postman or Insomnia.

![koa-5]

For our all routes to be more descriptive and follow REST API pattern, I have re-written every ctx.body object from each routing middleware function. Here is how the complete routing file looks so far.

https://gist.github.com/f634ba9ccec1b28c06e0659987370b21

![koa-6]


This completes the basics of building a REST API using Koa as a Node.js framework. It's a pretty minimal framework with all the necessary ways to tackle incoming requests and send the response back from the server. Koa also supports ready-made middleware functions to make use of for logging, handling errors, testing, compression, and security. Try them out.

You can find the complete code used in this tutorial at this Github repository 👇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment