Create a NodeJS API with Koa and TypeScript

In this tutorial series you will learn how to create a RESTful / JSON API using Koa 2, TypeScript, and Redis. You'll also work in a (partially) test driven development (TDD) fashion. I say partially, as often it's easiest to do a little "proof of concept" first, before writing tests.

By the end of this tutorial series you will have:

  1. Created a new Koa project
  2. Added TypeScript, third party typings, and created your own type definitions
  3. Set up Jest, and created tests for all the API endpoints
  4. Used Redis (through Docker) as a plug-in storage solution
  5. Created routes to handle GET, POST, and DELETE requests
  6. Added validation logic for incoming data

The goal of this tutorial series is to create a tested / testable JSON API that handles a single resource, which in our case will be a list of Games. You are completely free to switch this up.

You may be wondering: "What is Koa?"

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within its core, and it provides an elegant suite of methods that make writing servers fast and enjoyable.

That is taken straight from the docs.

With that said, Koa really isn't that new any more. Having been around since late 2013, by JavaScript standards Koa is practically an OAP.

Adding TypeScript makes some things easier, and some things that much harder. We'll make use of TypeScript to ensure the 'shape' of our data is as expected.

Jest is a fantastic JavaScript testing framework that works equally well for back end and front end projects. It will help ensure our API endpoints are behaving, and allow us to easily mock our our storage engine (Redis) when testing.

Redis is an in-memory data store which we will use as a very lightweight database. You could switch this out for a SQL database such as Postgres, but Redis's lists will serve our purposes just fine. We'll use Docker to run Redis (though you can run it any way you like), to make things even easier for ourselves.

Finally, validation is extremely useful - and something TypeScript won't be able to help us with directly. We'll make use of a third party library to make validation a breeze.

Ready to get started? Me too. Let's roll.


Presented By