Skip to content

Writing your first REST API

Koustuv Sinha edited this page Jan 24, 2016 · 2 revisions

Now I will show you a simple demonstration about how to write REST API's in Express. Be conversant about REST API from this amazing tutorial.

Suppose we want to write the following API :

GET /api/books

Which will list all the books in the database like this :

[
  {
    "_id": "56026b888fc48aa06912414a",
    "name": "Lords of the Rings",
    "isbn": "98288116210",
    "author": "56026b888fc48aa06912414q",
    "__v": 0,
    "goodreads": "",
    "price": 999,
    "borrowed": false,
    "owner" : "56026b888fc48aa069124azz"
  }, 
  ...
]

Follow these simple steps to create an API :

a. Create a Mongoose Model if not present

Here, since we would query a book, lets head over to models directory and create a model Books.js :

file : Books.js

/**
 * Books Model
 */

'use strict'

var mongoose = require('mongoose')

var Book = new mongoose.Schema({
  name: String,
  isbn: Number,
  author: mongoose.Schema.Types.ObjectId,   // reference to another mongodb document
  goodreads: String,
  price: Number,
  borrowed: Boolean
})

module.exports = mongoose.model('Book', Book)   // export the model for further use

b. Next, we move on to create the controller if not present. Lets name it Books Controller and place it in controller folder

file : books_controller.js

/**
 * Books Controller
 */

'use strict'

var Book = require('../models/Book')
var _ = require('lodash')

/**
 * Get all books
 * @api GET /api/books
 * @param  req request object
 * @param  res response object
 * @return {book object Array}
 */
exports.getAllBooks = function (req, res) {
  Book
    .find({})
    .exec(function (err, books) {
      if (err) {
        res.status(500).json({error : 'ServerError', message : 'Server Error' })
      } else {
        if (!_.isEmpty(books)) {
          res.status(200).json(books)
        } else {
          res.status(404).json({error : 'NoBooksFound', message : 'No Books found in database' })
        }
      }
    })
}

c. Now that the controller is done, all we need is to add the route. Open routes/api.js file and add the following line before module.exports :

var BooksController = require('../controller/books_controller')
router.get('/books', BooksController.getAllBooks)

d. Now you are all set. Open a terminal and start a mongo client, and add few records into the apnalibrary database

> use apnalibrary
switched to db apnalibrary
> db.books.insert({"name" : "Lord of the Rings", "isbn" : "9822982", "goodreads" : "", "price" : 899, "borrowed" : false, "author" : "", "owner" : "" })
WriteResult({ "nInserted" : 1 })
> db.books.find()
{ "_id" : ObjectId("56a4a0b4a33a3b3eeaed9447"), "name" : "Lord of the Rings", "isbn" : "9822982", "goodreads" : "", "price" : 899, "borrowed" : false, "author" : "", "owner" : "" }

e. Run the app and check the results! Congrats you have built your first REST API endpoint in NodeJS

NB : The models and api demonstrated here are just for educational purposes. Actual model will not correspond to this one!

Clone this wiki locally