paint-brush
RESTful API with Node.js for noobsby@jcapona
4,766 reads
4,766 reads

RESTful API with Node.js for noobs

by Jorge CáponaFebruary 27th, 2016
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

If you’re into web development, it’s likely that the terms API, REST, RESTful are familiar to you. As a beginner, I struggled (Still am) to get a layman definition of REST, and then, translating the concept into code.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - RESTful API with Node.js for noobs
Jorge Cápona HackerNoon profile picture

If you’re into web development, it’s likely that the terms API, REST, RESTful are familiar to you. As a beginner, I struggled (Still am) to get a layman definition of REST, and then, translating the concept into code.

The intention of this post is to give a shed of light to other beginners, and to show, through an example, how to develop a RESTful API using Node.js + Expressjs + MongoDB. At the bottom of the post, you’ll find the repository with the files we’ll be using along the way.

API: Application Programming Interface

An API is a set of programming routines, protocols, instructions and standards for accessing a web based application. It’s the layer of an application that can interact with other apps.

Looking at it as if our app is asking for data to an external app, we must first create the request in the correct format and send it to the app API we want to get the data from. The API reads the request, asks for the data to the app, then creates a response to the request and sends it back to our app.

Basic diagram

Nowadays, there are a lot of companies that release their API to the public, so that developers can make use of them for their own apps and software. As an example:

And the list goes on… ProgrammableWeb tracks 9000 Web APIs that were available in 2013, up from 105 in 2005. You see them in use in most of the pages you visit everyday. As a developer, you can use them too!

REST: Representational State Tranfer

REST was one of the things i couldn’t get the hang of when I first started studying it. According to Wikipedia:

REST is an architectural style consisting of a coordinated set of architectural constraints applied to components, connectors, and data elements, within a distributed hypermedia system

That really doesn’t say much (to me, at least), so I had to research and look for other definitions and explanations.

Taken from http://goo.gl/d5FUJp. Give it a read too!

Basically, REST is a design pattern, a way of designing a web application to expose resources on the web, using the HTTP protocol. These resources can be identified through a URL, such as:


http://www.myblog.com/posts/34http://www.hello.com//myList/5/item/12/

The REST server responses to these requests with ‘raw’ data and not a fancy HTML file. This ‘raw’ data uses JSON or XML (Among others) as media types for representing the resource.

To make operations on resources, REST uses pairs of request and responses, through 4 HTTP methods or ‘verbs’:

  • GET: to read a resource.
  • POST: to create a resource.
  • PUT: to update a resource.
  • DELETE: to delete a resource.

Non-REST vs REST comparison

From the image above, when you want to ‘read’ a specific user, you can go to /user/:id. Note that this path is also the same used when you want to update or delete a user. Also note how this is different from the non-REST approach.

When an API or server conforms to the constraints of REST, they can be called RESTful.

Implementation of a RESTful API in Node.js

For this example, we’ll develop an API where we’ll manage books. This API will allow us to perform CRUD operations in a database.

Start the repository using npm, we will use ‘index.js’ as our server file_:_

$ npm init

Then, install dependencies. We will use:

  • express’: Fast, unopinionated, minimalist web framework for Node.js.
  • body-parser’: Node.js body parsing middleware.
  • method-override’: Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn’t support it.
  • mongoose’: Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.

To install them, type:

$ sudo npm install express body-parser method-override mongoose --save

Then, in ‘index.js’ file, write:





var express = require("express");var app = express();var bodyParser = require("body-parser");var methodOverride = require("method-override");var mongoose = require("mongoose");




// App configurationapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));app.use(methodOverride());



app.get("/", function(req, res) {res.send("Hello World!");});



app.listen(5000, function(){console.log("index.js listening on port 5000");})

Up to this point, we have a server, listening on port 5000 to GET requests on the ‘/’ route. The skeleton of the file is similar to the one presented in my previous post. The difference is that now we are using the packages that we installed in the previous step.

Creating the Models for our app

The Model represents the information of the application and the rules used to manipulate the data. In our case, our model will represent a book.

We will place the model, called ‘Book.js’, inside a ‘models’ folder. This file contains the representation of a book: title, author, ISBN code, year of publication, summary, among others. Then, we use “module.exports” to use this model file from other files.

The Book model file ‘Book.js’ is the following:




/**Model file of a Book*/var mongoose = require("mongoose");







var BookSchema = new mongoose.Schema({title: { type: String, required: true },author: { type: String, required: true },isbn: { type: String, required: true },pages: { type: Number },summary: { type: String }});

var Book = mongoose.model("books", BookSchema);



module.exports = {BookModel: Book};

Creating a local database using MongoDB

To manage the books, we need a running database. For the purposes of this example, we’ll use a local Mongo database. To create the database that we’ll use with out app, run the commands from the next image.

Creating a local mongo database called ‘books’

If you run the ‘show dbs’ command inside the mongo shell, you will, most likely, not see the new ‘books’ database, since it’s empty.

To connect to the database using ‘mongoose’ , in the ‘index.js’ file add the following line:

mongoose.connect("mongodb://localhost/books");

Implementation of CRUD operations

So, we have the model of a book, and a local database called ‘books’. Now, we have to modify our app code, the ‘index.js’ file, so that we are able to create, read, update & delete books from our database.

To manage what our app will do for every route or action requested, we will use a controller, specifically, a BookController. Create a folder ‘controllers’, and inside, place the ‘BooksController.js’ file.

We have to tell our ‘index.js’ file that our BooksController will manage all the operations related to book management. This is done by adding the following:






var BooksController = require("./controllers/BooksController");app.post("/book",BooksController.create); // Createapp.get("/book/:id",BooksController.readOne); // Read Oneapp.get("/book/",BooksController.readAll); // Read Allapp.put("/book/:id",BooksController.update); // Updateapp.delete("/book/:id",BooksController.delete); // Delete

These lines tell our server that if receives a POST request to the ‘/book’ route, the routine ‘create’ in our ‘BooksController.js’ file will manage it.

Final index.js file. You can find the code in the Github repo. Keep reading!

Also, there are 2 GET routes: ‘/book’ and ‘/book/:id’; the first one will return all the books in our DB, and the second one will only display the one with the id used as argument.

Our newly created ‘BooksController.js’ file should have this form:



/**Book Controller file*/

var Book = require("../models/Book.js");



// Inserts a book to the dbexports.create = function(req, res){};



// Finds a single book in the dbexports.readOne = function (req, res) {};



// Finds all books in the dbexports.readAll = function (req, res) {};



// Updates a book from the dbexports.update = function(req, res) {};



// Deletes a book from the dbexports.delete = function(req, res) {};

Where inside every function block is the code to manage our books, and interact with our database. There’s not much to explain here, inside ever function we simply perform the basic CRUD operations using mongoose & our book model.

BookController. You can find the code in the Github repo. Keep reading!

Testing our API

To easily test our API, we’ll use POSTMAN. This is basically a HTTP client for testing web services. There are other apps that do similar things, but POSTMAN is lightweight & very simple to use.

First, we’ll create our first book resource. Open POSTMAN and select a POST operation on ‘localhost:5000/book’. Now, fill the keys and values of the book you want to insert to the database. Finally, press ‘Send’ and check the response from the server. If nothing goes wrong, you should receive a JSON with the data of the created book in the database.

Using POSTMAN to test our API

To see our first saved book, using POSTMAN with a GET request, go to the URL (You can check this in your browser too):

http://localhost:5000/book/

This should print all the books in our database (Only one at this point).

To read only one book in particular, use the URL:

http://localhost:5000/book/56d37e1430678fde6e037e27

Where the code after ‘/book/’ corresponds to the ‘_id’ of the book you want to read.

You can now play with our API, create, read, update and delete books as you want :).

Final comments

I hope this helps the reader to have a better understanding of what REST is, and lighten the way on how to develop a proper RESTful API.

If you look around, there are several frameworks that will automatically create and manage the model & controller files for you, but if you’re a beginner, it’s important to know the foundations and have an idea of how it works before you get all the job done with a single line command in your shell.

If you have any comments or corrections (I’m a noob too!), just let me know!

The Code

You can find the code @Github