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.
brew 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.
curl -sL http://ift.tt/2rqglBp | sudo -E bash - sudo apt-get install -y nodejs
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.
mkdir restify-api cd restify-api
Now initialize your package.json by running the command:
npm init
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.
npm install restify mongoose mongoose-api-query mongoose-timestamp lodash winston bunyan-winston-adapter restify-errors restify-plugins --save
The packages will be installed in your node_modules folder. Your package.json file should look similar to what I have below.
#package.json { "name": "restify-api", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "bunyan-winston-adapter": "^0.2.0", "lodash": "^4.17.4", "mongoose": "^4.11.2", "mongoose-api-query": "^0.1.1-pre", "mongoose-timestamp": "^0.6.0", "restify": "^5.0.0", "restify-errors": "^4.3.0", "restify-plugins": "^1.6.0", "winston": "^2.3.1" } }
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:
mongo use restify-api
Now you can go ahead and set up your configuration.
touch config.js
The file should look like this:
#config.js 'use strict' module.exports = { name: 'RESTIFY-API', version: '0.0.1', env: process.env.NODE_ENV || 'development', port: process.env.port || 3000, base_url: process.env.BASE_URL || 'http://localhost:3000', db: { uri: 'mongodb://127.0.0.1:27017/restify-api', } }
Set Up the To-Do Model
Create your to-do model. First, you create a directory called models.
mkdir models touch todo.js
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.
#models/todo.js 'use strict' // Requires module dependencies installed using NPM. const mongoose = require('mongoose'), mongooseApiQuery = require('mongoose-api-query'), // adds created_at and modified_at timestamps for us (ISO-8601) timestamps = require('mongoose-timestamp') // Creates TodoSchema const TodoSchema = new mongoose.Schema({ // Title field in Todo collection. title: { type: String, required: true, trim: true, }, }, { minimize: false }) // Applies mongooseApiQuery plugin to TodoSchema TodoSchema.plugin(mongooseApiQuery) // Applies timestamp plugin to TodoSchema TodoSchema.plugin(timestamps) // Exports Todo model as a module. const Todo = mongoose.model('Todo', TodoSchema) module.exports = Todo
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.
mkdir routes touch index.js
Set it up like so:
#routes/index.js 'use-strict' // Requires module dependencies installed using NPM. const _ = require('lodash') errors = require('restify-errors') // Requires Todo model const Todo = require('../models/todo') // HTTP POST request server.post('/todos', (req, res, next) => { // Sets data to the body of request let data = req.body || {} // Creates new Todo object using the data received let todo = new Todo(data) // Saves todo todo.save( (err) => { // If error occurs, error is logged and returned if (err) { log.error(err) return next(new errors.InternalError(err.message)) //next() } // If no error, responds with 201 status code res.send(201) next() }) }) // HTTP GET request server.get('/todos', (req, res, next) => { // Queries DB to obtain todos Todo.apiQuery(req.params, (err, docs) => { // Errors are logged and returned if there are any if (err) { log.error(err) return next(new errors.InvalidContentError(err.errors.name.message)) } // If no errors, todos found are returned. res.send(docs) next() }) }) //HTTP GET request for individual todos server.get('/todos/:todo_id', (req, res, next) => { // Queries DB to obtain individual todo based on ID Todo.findOne({_id: req.params.todo_id}, (err, doc) => { // Logs and returns error if errors are encountered if (err) { log.error(err) return next(new errors.InvalidContentError(err.errors.name.message)) } // Responds with todo if no errors are found res.send(doc) next() }) }) // HTTP UPDATE request server.put('/todos/:todo_id', (req, res, next) => { // Sets data to the body of request let data = req.body || {} if (!data._id) { _.extend(data, { _id: req.params.todo_id }) } // Finds specific todo based on the ID obtained Todo.findOne({ _id: req.params.todo_id }, (err, doc) => { // Logs and returns error found if (err) { log.error(err) return next(new errors.InvalidContentError(err.errors.name.message)) } else if (!doc) { return next(new errors.ResourceNotFoundError('The resource you request could not be found.')) } // Updates todo when the todo with specific ID has been found Todo.update({ _id: data._id }, data, (err) => { // Logs and returns error if (err) { log.error(err) return next(new errors.InvalidContentError(err.errors.message)) } // Responds with 200 status code and todo res.send(200, data) next() }) }) }) // HTTP DELETE request server.del('/todos/:todo_id', (req, res, next) => { // Removes todo that corresponds with the ID received in the request Todo.remove({ _id: req.params.todo_id }, (err) => { // Logs and returns error if (err) { log.error(err) return next(new errors.InvalidContentError(err.errors.message)) } // Responds with 204 status code if no errors are encountered res.send(204) next() }) })
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.
#index.js 'use strict' // Requires module dependencies downloaded with NPM. const config = require('./config'), restify = require('restify'), bunyan = require('bunyan'), winston = require('winston'), bunyanWinston = require('bunyan-winston-adapter'), mongoose = require('mongoose') // Sets up logging using winston logger. global.log = new winston.Logger({ transports: [ // Creates new transport to log to the Console info level logs. new winston.transports.Console({ level: 'info', timestamp: () => { return new Date().toString() }, json: true }), ] }) /** * Initialize server */ global.server = restify.createServer({ name : config.name, version : config.version, log : bunyanWinston.createAdapter(log) }) /** * Middleware */ server.use(restify.plugins.bodyParser({ mapParams: true })) server.use(restify.plugins.acceptParser(server.acceptable)) server.use(restify.plugins.queryParser({ mapParams: true })) server.use(restify.plugins.fullResponse()) // Error handler to catch all errors and forward to the logger set above. server.on('uncaughtException', (req, res, route, err) => { log.error(err.stack) res.send(err) }) // Starts server server.listen(config.port, function() { // Connection Events // When connection throws an error, error is logged mongoose.connection.on('error', function(err) { log.error('Mongoose default connection error: '+ err) process.exit(1) }) // When connection is open mongoose.connection.on('open', function(err) { // Error is logged if there are any. if (err) { log.error('Mongoose default connection error: ' + err) process.exit(1) } // Else information regarding connection is logged log.info( '%s v%s ready to accept connection on port %s in %s environment.', server.name, config.version, config.port, config.env ) // Requires routes file require('./routes') }) global.db = mongoose.connect(config.db.uri) })
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:
node index.js
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:
{ "title" : "Restify rocks!" }
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