Create REST-Service with Node.js Express in 10 mins

Datetime:2016-08-23 01:52:54          Topic: REST           Share

Single Page Applications ( SPA ) are very popular today. They are fast, easy to develop, scalable in terms of server load. SPA in front-end is client-side assets: HTML templates, stylesheets, and JS scripts, loaded on the first page load. And what is on the backend? The backend is usually a RESTful service , which provides data to front-end and manages change requests.

In this post we will see how to create a simple REST service supporting CRUD operations , using Node.js Express framework.

Let's say we have a list of clients that we want to manage. We'd like to display the grid with all existing clients, filter the data, add, edit, and delete clients.

Look at the app we are going to build on the demo page .

The source code is on GitHub .

REST service endpoint API supporting CRUD operations should look like:

  • GET /clients - returns a list of clients
  • POST /clients - creates a new client
  • PUT /clients - updates an existing client
  • DELETE /clients - removes a client

Now let's get our hands dirty and do some coding.

Create Application

Express application generator allows to create the application skeleton in a minute.

Install the Express application generator with npm:

$ npm install express-generator -g

And generate the application with the command:

$ express myapp

Go in the app directory and install all npm dependencies:

$ cd myapp
$ npm install

As a result we get the project with the following structure:

  • bin/www - a script starting the application
  • public/ - contains front-end part of the app: scripts, stylesheets, and images
  • routes/ - contains scripts defining the routing
  • views/ - views and layout
  • app.js - app configuration script

Now let's implement our API.

Get Clients List

Remove sample routes/users.js script and its references from app.js and add routes/clients.js - the route script to be able to access our clients data.

For simplicity we'll use static JSON file with the list of clients. Add a file db/clients.json and paste inside these JSON containing demo clients data.

The structure of client JSON is the following:

{
  "Name": "Connor Johnston",
  "Age": 35,
  "Country": 7,
  "Address": "Ap #370-4647 Dis Av.",
  "Married": false
}

We use the database engine NeDB , in-memory DB for Node.js, to keep it simple.

Install NeDB with npm:

$ npm install nedb --save

Put the Datastore initialization code into the clients.js :

var clientsData = require('../db/clients.json');
var Datastore = require('nedb');
var db = new Datastore();
db.insert(clientsData);

Define the route to request client list with HTTP GET to '/clients' endpoint:

router.get('/', function(req, res, next) {
    db.find(getClientFilter(req.query), function(err, items) {
        res.json(items);
    });
});

Our endpoint allows filtering clients by different fields. The filter is provided in the HTTP request query string. The function getClientFilter retrieves filter data from the query parameters:

var getClientFilter = function(query) {
    var result = {
        Name: new RegExp(query.Name, "i"),
        Address: new RegExp(query.Address, "i")
    };

    if(query.Married) {
        result.Married = query.Married === 'true' ? true : false;
    }

    if(query.Country && query.Country !== '0') {
        result.Country = parseInt(query.Country, 10);
    }

    return result;
};

Require our new client.js and define the route '/clients' in app.js :

var routes = require('./routes/index');
var clients = require('./routes/clients');

...

app.use('/', routes);
app.use('/clients', clients);

That's it, run the application with the command:

$ npm start

Сall the endpoint opening the url http://localhost:3000/clients to see the list of clients in JSON format.

Create New Client

To create a new client we should handle the HTTP POST request to the '/clients' endpoint.

router.post('/', function(req, res, next) {
    db.insert(prepareItem(req.body), function(err, item) {
        res.json(item);
    });
});

We send the inserted item in the response.

As all data fields are coming in the request as strings, we need to parse Country (numeric) and Married (boolean) fields. That's what prepareItem method does:

var prepareItem = function(source) {
    var result = source;
    result.Married = source.Married === 'true' ? true : false;
    result.Country = parseInt(source.Country, 10);
    return result;
};

Update Existing Client

To update an existing client we handle HTTP PUT request to the '/clients' endpoint.

router.put('/', function(req, res, next) {
    var item = prepareItem(req.body);

    db.update({ _id: item._id }, item, {}, function(err) {
        res.json(item);
    });
});

As for the creation, we send an updated item in the response.

Delete Client

HTTP DELETE request to the '/clients' endpoint removes a client by id:

router.delete('/', function(req, res, next) {
    var item = prepareItem(req.body);

    db.remove({ _id: item._id }, {}, function(err) {
        res.json(item);
    });
});

Demo Page

Now let's add a demo page to be able to test our REST service and try filtering, creation, updating, and deletion. To display the grid with clients we use lightweight table control jsGrid .

Change the layout.jade adding three placeholders: head block for <head> section, content for the page content, and scripts for scripts at the bottom of the page. We also need to add a reference to jQuery, since jsGrid depends on it.

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/css/style.css')
    block head
  body
    header
      h1= title
    block content

    script(src='https://code.jquery.com/jquery-2.2.4.min.js')
    block scripts

Now, change the main page of our application index.jade to use our layout:

extends layout

block head
  link(href='https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.1/jsgrid.min.css', rel='stylesheet')
  link(href='https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.1/jsgrid-theme.min.css', rel='stylesheet')

block content
  div#jsGrid

block scripts
  script(src='https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.1/jsgrid.min.js')
  script(src='/js/sample.js')

In the head block we put links to the jsGrid stylesheets. In the content block we add a single div for the grid. The scripts block contains references to jsGrid and sample.js - a script to initialize the grid.

The new script sample.js contains grid initialization:

$(function() {

    // List of countries for the select field
    var countries = [
        { Name: "", Id: 0 },
        { Name: "United States", Id: 1 },
        { Name: "Canada", Id: 2 },
        { Name: "United Kingdom", Id: 3 },
        { Name: "France", Id: 4 },
        { Name: "Brazil", Id: 5 },
        { Name: "China", Id: 6 },
        { Name: "Russia", Id: 7 }
    ];

    $("#jsGrid").jsGrid({
        height: "70%",
        width: "100%",
        filtering: true,
        inserting: true,
        editing: true,
        sorting: true,
        paging: true,
        autoload: true,
        pageSize: 10,
        pageButtonCount: 5,
        deleteConfirm: "Do you really want to delete client?",
        controller: {
            loadData: function(filter) {
                // GET to retrieve client list
                return $.ajax({
                    type: "GET",
                    url: "/clients",
                    data: filter
                });
            },
            insertItem: function(item) {
                // POST to create new client
                return $.ajax({
                    type: "POST",
                    url: "/clients",
                    data: item
                });
            },
            updateItem: function(item) {
                // PUT to update the client
                return $.ajax({
                    type: "PUT",
                    url: "/clients",
                    data: item
                });
            },
            deleteItem: function(item) {
                // DELETE to remove client
                return $.ajax({
                    type: "DELETE",
                    url: "/clients",
                    data: item
                });
            }
        },
        fields: [
            { name: "Name", type: "text", width: 150 },
            { name: "Age", type: "number", width: 50, filtering: false },
            { name: "Address", type: "text", width: 200 },
            { name: "Country", type: "select", items: countries, valueField: "Id", textField: "Name" },
            { name: "Married", type: "checkbox", title: "Is Married", sorting: false },
            { type: "control" }
        ]
    });

});

The detailed grid config description can be found in the documentation . The most important is the grid controller option. It has functions making ajax calls to our REST service on CRUD operations:

  • loadData - loads data to the grid sending the GET request to '/clients'
  • insertItem - inserts an item sending POST request to '/clients'
  • updateItem - updates an existing item sending PUT request to the '/clients'
  • deleteItem - deletes an item sending DELETE request to the '/clients'

Now start the application running npm start and open the url http://localhost:3000/ .

The result should look like this:

Find the app we've just built following the link .

Conclusion

We saw how to create a REST service supporting CRUD operations with Node.js Express framework and how to plug this service to the front-end application - a page with the client-side grid control jsGrid .

Thank you for reading. Feel free to share your thoughts in the comments below.





About List