Monday, September 11, 2017

Build a To-Do API With Node and Restify

Build a To-Do API With Node and Restify

Introduction

Restify is a Node.js web service framework optimized for building semantically correct RESTful web services ready for production use at scale. In this tutorial, you will learn how to build an API using Restify, and for learning purposes you will build a simple To-Do API.

Set Up the Application

You need to have Node and NPM installed on your machine to follow along with this tutorial.

Mac users can make use of the command below to install Node.

Windows users can hop over to the Node.js download page to download the Node installer.

Ubuntu users can use the commands below.

To show that you have Node installed, open your terminal and run node -v. You should get a prompt telling you the version of Node you have installed.

You do not have not install NPM because it comes with Node. To prove that, run npm -v from your terminal and you will see the version you have installed.

Create a new directory where you will be working from.

Now initialize your package.json by running the command:

You will be making use of a handful of dependencies:

  • Mongoose
  • Mongoose API Query (lightweight Mongoose plugin to help query your REST API)
  • Mongoose TimeStamp (adds createdAt and updatedAt date attributes that get auto-assigned to the most recent create/update timestamps)
  • Lodash
  • Winston (a multi-transport async logging library)
  • Bunyan Winston Adapter (allows the user of the winston logger in restify server without really using bunyan—the default logging library)
  • Restify Errors
  • Restify Plugins

Now go ahead and install the modules.

The packages will be installed in your node_modules folder. Your package.json file should look similar to what I have below.

Before you go ahead, you have to install MongoDB on your machine if you have not done that already. Here is a standard guide to help you in that area. Do not forget to return here when you are done.

When that is done, you need to tell mongo the database you want to use for your application. From your terminal, run:

Now you can go ahead and set up your configuration.

The file should look like this:

Set Up the To-Do Model

Create your to-do model. First, you create a directory called models.

You will need to define your to-do model. Models are defined using the Schema interface. The Schema allows you to define the fields stored in each document along with their validation requirements and default values. First, you require mongoose, and then you use the Schema constructor to create a new schema interface as I did below. I also made use of two modules called mongooseApiQuery and timestamps.

MongooseApiQuery will be used to query your collection (you will see how that works later on), and timestamps will add created_at and modified_at timestamps for your collection.

The file you just created should look like what I have below.

Set Up the To-Do Routes

Create another directory called routes, and a file called index.js. This is where your routes will be set.

Set it up like so:

The file above does the following:

  • Requires module dependencies installed with NPM.
  • Performs actions based on the request received.
  • Errors are thrown whenever one (or more) is encountered, and logs the errors to the console.
  • Queries the database for to-dos expected for listing all to-dos, and posting to-dos.

Now you can create the entry for your application. Create a file in your working directory called index.js.

You have set up your entry file to do the following:

  • Require modules installed using NPM.
  • Output info level logs to the console using Winston Logger. With this, you get to see all the important interactions happening on your application right on your console.
  • Initialize the server and set up middleware using Restify plugins.
  • bodyParser parses POST bodies to req.body. It automatically uses one of the following parsers based on content type:
    • acceptParser accepts the header.
    • queryParser parses URL query parameters into req.query.
    • fullResponse handles disappeared CORS headers.
  • Next, you start your server and create a mongoose connection. Logs are outputted to the console dependent on the result of creating the mongoose connection.

Start up your node server by running:

Open up postman and send an HTTP POST request. The specified URL should be http://locahost:3000/todos.

For the request body, you can use this:

And you should get a response.

Conclusion

You have been able to build a standard To-Do API using Restify and Node.js. You can enhance the API by adding new features such as descriptions of the to-dos, time of completion, etc.

By building this API, you learned how to create logs using Winston Logger—for more information on Winston, check the official GitHub page. You also made use of Restify plugins, and more are available in the documentation for plugins.

You can dig further into the awesomeness of Restify, starting with the documentation.


No comments:

Post a Comment