Hello and welcome to part 1 of my tutorial series Building a REST API with Node, Express and Mongo. As the title suggests we will cover how to build a simple API for a blog. Before we get started lets define the requirements for this project so we can refer back to them as needed:

  • The API should:
    • Provide the ability to create users, posts and categories
    • Provide the ability to update user and post information
    • Provide the ability to query for all posts, a single post and posts by authors / tags
  • All endpoints should follow RESTful patterns and principles
  • Once the API has been built it should be automatically tested for any flaws
  • There will no frontend interface
  • Authentication will be out of scope for this series - OAuth 2.0 is a topic on its own

As we are using a multitude of tools through the course of this series I cannot cover the installation of all of them - External links will be provided as and when needed.

With that in mind lets look at the tools we'll be using:

The Tools

  • NPM - NPM is a package manager that is shipped with Node by default. It allows us to define a package.json file which holds our dependencies allowing us to easily manage our application's installation. Here is the NPM Website
  • Gulp - Gulp is an automation tool that is built on top of Node. How many times as a developer have you had to do tasks by hand like linting, minifying etc? Well Gulp takes the pain out of that and allows us to define async tasks that are run on certain events. Extremely useful when it comes to testing later! Check out the Gulp Website
  • Mocha - Mocha is a simple testing framework which allows us to define suites of tests to test our API. It has gulp plugins available and integrates nicely with Chai an assertion library we will use to check our data flow. Check out the Mocha Website
  • Express (Node) - Express is a lightweight un opinionated web framework which allows developers to create web applications without needing to get bogged down into the intricacies of HTTP modules. This will form the backbone to our API. Check out the Express Framework Website
  • MongoDB - Lastly a by certainly no means least MongoDB - MongoDB is JSON Document object store and will form the persistent data layer of our application. As NodeJS understands JSON natively it is a logical choice for our data and can be presented by the API in its raw form - Check out the MongoDB Website

Project Setup

Follow along with the tutorial to get an identical setup or if you'd rather jump ahead all code is available from this repo https://bitbucket.org/dylanrhysscott94/series-rest-api

Prerequisites

  1. Install NodeJS - https://nodejs.org/en/download/package-manager/
  2. Install MongoDB - https://docs.mongodb.com/manual/installation/#tutorials
  3. Install the additional system dependencies - librk5-dev, build-essential and make via Homebrew or Apt-Get as appropriate
  4. From the terminal install the Express App generator - This gives us a way of quickly generating an express application to start from. Run npm install -g express-generator

Generating the app

  1. To generate our base app run express blog-api - You should see output similar to this:
  warning: the default view engine will not be jade in future releases
  warning: use `--view=jade' or `--help' for additional options


   create : blog-api
   create : blog-api/package.json
   create : blog-api/app.js
   create : blog-api/public
   create : blog-api/public/images
   create : blog-api/public/javascripts
   create : blog-api/public/stylesheets
   create : blog-api/public/stylesheets/style.css
   create : blog-api/routes
   create : blog-api/routes/index.js
   create : blog-api/routes/users.js
   create : blog-api/views
   create : blog-api/views/index.jade
   create : blog-api/views/layout.jade
   create : blog-api/views/error.jade
   create : blog-api/bin
   create : blog-api/bin/www

   install dependencies:
     $ cd blog-api && npm install

   run the app:
     $ DEBUG=blog-api:* npm start
  1. Install and run the application with the following command cd blog-api && npm install && DEBUG=blog-api:* npm start. If all goes well you should see the dependencies install and our app run on http://localhost:3000

express-app-running

Tailoring our project

Before we get started in further lessons the generator has given us some additional files that we don't need for an API project. Stop the running app with CTRL+C and do the following:

  1. In app.js remove the following lines relating to favicons, views and cookies:
var path = require('path');  
var favicon = require('serve-favicon');  
var cookieParser = require('cookie-parser');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

// view engine setup
app.set('views', path.join(__dirname, 'views'));  
app.set('view engine', 'jade');

app.use(cookieParser());  
app.use(express.static(path.join(__dirname, 'public')));

// error handler
app.use(function(err, req, res, next) {  
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
  1. Delete the views/ and public/ directories
  2. Change res.render('index', { title: 'Express' }); to res.status(200).json({message: "index"});
  3. Run npm remove jade cookie-parser serve-favicon --save
  4. Restart the app DEBUG=blog-api:* npm start - You should now see our index serving JSON instead of a template

express-serving-json

Wrapping Up...

That's it - our project is setup and ready to go! We have a solid base to start build our API in future lessons. There maybe some adjustments we will make to our project environment as we need them but for now this will be a good start.

Keep an eye for the next part in the series

Has this tutorial been useful? - Please give me feedback via my twitter handle @dylanrhysscott!