Billy Chandler

Billy Chandler

1559619853

Restful API with NodeJS, Express, PostgreSQL, Sequelize, Travis, Mocha, Coveralls and Code Climate

NodeJS is becoming a backend language of choice for many developers.

In this article, I am going to work you through building a Simple Restful API with:

  • NodeJS — For writing Javascript server-side applications
  • Express — A NodeJS framework
  • PostgreSQL — An open source object-relational database
  • Sequelize — An ORM(Object Relational Mapping) of PostreSQL
  • Travis —A continuous integration service for Testing Applications
  • Coveralls — **A **web service to help you track your code coverage over time.
  • Code Climate — Provides automated code review for maintainability and test coverage.
  • Babel — To convert ES6 javascript code to ES5

Though overwhelming, but you learn how to use these technologies simultaneously.

Let’s Build This!

This project is going to be built from scratch, without webpack, browserify or Gulp.

Step 1:

Setting Environment and Installing Dependencies:

a. Create a new directory called **book-app **and switch to that directory

mkdir book-app
cd book-app

b. Initialise npm and follow the instructions

npm init -y

c. Install Express and Body-parser:

npm install --save express body-parser

d. Install babel: Because we need to convert our ES6 code to ES5. Install babel dependencies by copying the code below and paste in the terminal of the working directory:

npm install --save-dev @babel/core @babel/cli @babel/node @babel/plugin-transform-runtime @babel/preset-env @babel/register @babel/runtime babel-loader

Create the .babelrc file in the path: /book-app/ and populate it with*:*

{
   "presets": ["@babel/preset-env"],
   "plugins": [["@babel/transform-runtime"]]
}

e. Install eslint and airbnb style guide. This is Optional!

This will help you format your code in an easy to read state.

npm install --save-dev eslint eslint-config-airbnb-base eslint-plugin-import

Create a file .eslintrc.js in the path: /book-app/

This the way i configured mine:

module.exports = {
  "extends": "airbnb-base",
"rules": {
"no-console": 0,
"no-param-reassign": [2, {"props": false}],
"prefer-destructuring": 0,
"treatUndefinedAsUnspecified": true,
"arrow-body-style": 0,
"comma-dangle": 0,
},
"env": {
"commonjs": true,
"node": true,
"mocha": true
},
};

Of course, you can setup yours however you wish.

f. Install nodemon:

In the cause of this tutorial, we will need to run node server over and over again. Nodemon is like a watcher that automatically restarts the server each time changes are made. You can install it globally using:

npm install -g nodemon

Note that this installation will not be in this project package.json file, because it was installed globally.

g. Including nodemon in the package.json file:

Open the package.json file, edit the scripts object as follows:

"scripts": {
  "dev": "nodemon --exec babel-node ./api/index.js",
  "test": "echo \"Error: no test specified\" && exit 1"
}

Observe the** ./api/index.js** ? Don’t worry, we will create the file in step 2.

At this point, your package.json file should look like this:

{
"name": "book-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon --exec babel-node ./api/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
  "body-parser": "^1.18.3",
  "express": "^4.16.4"
},
"devDependencies": {
  "@babel/cli": "^7.4.3",
  "@babel/core": "^7.4.3",
  "@babel/node": "^7.2.2",
  "@babel/plugin-transform-runtime": "^7.4.3",
  "@babel/preset-env": "^7.4.3",
  "@babel/register": "^7.4.0",
  "@babel/runtime": "^7.4.3",
  "babel-loader": "^8.0.5"
  }
}

h. Structuring the application:

Create a directory called api . Then create the index.js file, which is the root file for this application. You should be in the path: book-app/api/

touch index.js

Change to the api directory and create another directory called server. Your directory tree should now look like this:

book-app
├── api
│   ├── server
├── ├── index.js
├── node_modules
├── package.json
└── package-lock.json

Step 2:

Edit the index.js file and start the server

a. Edit the index.js file:

import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const port = process.env.PORT || 8000;
// when a random route is inputed
app.get('*', (req, res) => res.status(200).send({
   message: 'Welcome to this API.'
}));
app.listen(port, () => {
   console.log(`Server is running on PORT ${port}`);
});
export default app;

b. Start the server

Since we have defined the script to start the server, we simply run in the terminal from the path: /book-app/api/:

npm run dev

Hopefully you will see nodemon running in the terminal, with the port number the server is running on:

Step 3

Setup PostreSQL Database

a. Install:

If you don’t already have postreSQL running in your machine, you can download it and setup it.

If you are on a mac OS, you can follow this instruction: https://medium.com/@Umesh_Kafle/postgresql-and-postgis-installation-in-mac-os-87fa98a6814d

For Windows users: http://www.postgresqltutorial.com/install-postgresql/

For Ubuntu users: https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-18-04

**b. Setup: **You can use the default user called: postgres or you can create a new user. There is probably hundreds of materials out there that can help you achieve this.

If you have any issues installing and setting up postgreSQL on your local machine, you can use an online database such as ElephantSQL

Step 4

Setup Sequelize

Sequelize is an ORM(Object Relational Mapping) for PostgreSQL. What this means is that, instead of writing raw SQL queries, ORM is used instead, which makes work easier.

a. Install sequelize cli globally:

npm install -g sequelize-cli

Note, if you wish not to install this globally, you’ll need to prefix every call to the sequelize command with ./node_modules/.bin

b. Create the file: **.sequelizerc **in the path: /boook-app/. That is, outside of the api folder.

touch .sequelizerc

Write in the file, the code below

const path  = require('path')
module.exports = {
    "config": path.resolve('./api/server/src/config', 'config.js'),
    "models-path": path.resolve('./api/server/src/models'),
    "seeders-path": path.resolve('./api/server/src/seeders'),
    "migrations-path": path.resolve('./api/server/src/migrations')
};

Observe that we required path. Let’s quickly install it:

npm install --save path

c. Install postgreSQL and sequelize dependencies

npm install --save sequelize pg pg-hstore

Where: pg = postgreSQL and pg-hstore = converts data into the Postgres hstore format.

d. Initialize Sequelize:

This will generate the Sequelize boilerplate which includes, models, migrations and seeders. Run:

sequelize init

The directory tree should now resemble this:

book-app
├── api
│   └── index.js
│   ├── server
│   │   └── src
│   │       └── config
│   │       ├── └── config.js
│   │       └── migrations
│   │       └── models
│   │       ├── └── index.js
│   │       └── seeders│  
├── .babelrc
└── .eslintrc.js
└── .sequelizerc
└── package.json
└── package-lock.json

e. Edit the book-app/api/server/models/index.js file.

This is the current state:

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

We will use ES6 syntax.

So, book-app/api/server/models/index.js becomes:

f. Editing the config.js file:

Let’s quickly install dotenv package. This will make it easier when using .env variables

npm install --save dotenv

Now, the config.js file:

You can replace the username with the one you used while setting up your postgreSQL. If you don’t remember creating a username, It means you are using the default user, which is postgres . For the password if you created a user, use the password, else, leave it the way it is above.

Also, incase you are using an online database, such as ElephantSQL, uncomment this lines:

development: {
   use_env_variable: 'DATABASE_URL'
},

Then, you will export the database URL into your environment

export DATABASE_URL=our-database-url

where our-database-url is the URL we copied from ElephantSQL. Every time you need to run this application, you will need to export the DATABASE_URLfirst.

Remember, if you decide to use the online database, and have uncommented the line above, comment the development setup for the local PostgreSQL database. So as to avoid name duplication.

g. Create a .env file in the path: /book-app/.

DB_NAME=books
DB_USER=steven
DB_PASS=
DB_PORT=5432
DB_HOST=127.0.0.1
SECRET_KEY=any_secret

h. Use Database GUI(Graphical User Interface): Optional.

Instead of doing all database operations in the terminal, which is very painful for some, you can use a GUI such as pgadmin or tableplus

Step 5

Create Databases, Model and Migration

a. Create the Databases:

In the config.js file above, we referenced a database called books for development and book_test for testing. You can either use the GUI or Terminal to create these databases.

Before you run any command, ensure that the PostgreSQL server is running, on mac OS, run:

pg_ctl -D /usr/local/var/postgres start  //For mac OS
or:
brew services start postgresql    //To always run it on mac OS

pg_ctl -D "C:\Program Files\PostgreSQL\9.6\data" start 
//For Windows. Observe the 9.6, yours may be different

sudo service postgresql start //For Linux

Get the list of commands here.

Now, Creating the databases from the terminal:

createdb books
createdb book_test

b. Create the Model

We are creating just one model: book.js

sequelize model:create --name Book --attributes title:string, price:string, description:string

Locate** book.js** in the path: /book-app/api/server/src/models/

Using ES6 syntax and adding to the file, we have:

c. Refactor migration file

A migration file was also created when we ran that command to create the model, located in the path: …server/migrations/<date>-create-book.js

Edit the migration file to have:

Save all files and run migration:

sequelize db:migrate

You can check in the database to confirm if migration ran successfully.

Step 6

Create Services, Controllers, Routes and Utilities

Yes, we can put all the code in one file. But that is not best practice. So, is good we separate code into different files. We will create four folders in the path: /book-app/api/server:

book-app
├── api
    ├── server
        ├── controllers
        ├── routes
        ├── services
        ├── utils

a. Services:

You might ask, what is a Service? See it as a medium that helps us interface with our book model.

In the Services folder, create a file: BookService.js

b. Controllers

The Service file created above is used in our controller. Create a file called BookController.js in the controllers folder

This is the content:

c. Utilities

As seen, in the BookController.js file, we imported a file called Utils.js. This file contain all the responses we will assert for while running and testing the api endpoints.

Create the Utils.js file in the Utils folder.

Its content is:

d. Routes

Create the route file called BookRoutes.js in the routes folder.

Its content:

e. Editing the /book-app/api/index.js file to add the route file defined above:

Step 7

Running Endpoints

Time to see results!

We can test the endpoint using postman app or any API testing tool of your choice.

Start up the server, if you terminated it before:

npm run dev

If you dont know how to use postman, you might need to learn the basics, before continuing.

a. POST a book:

In the postman address bar enter this:

http://localhost:8000/api/v1/books    //POST

Change the http method to POST, then define the json data to post in the body

As an example:

b. GET all books

http://localhost:8000/api/v1/books    //GET

c. GET a particular book

http://localhost:8000/api/v1/books/:id    //GET

d. UPDATE a particular book

http://localhost:8000/api/v1/books/:id    //PUT

e. DELETE a particular book

http://localhost:8000/api/v1/books/:id    //DELETE

Step 8

Write Test Cases for Endpoints

I hope, all your endpoint worked as expected.

Now, let’s write test cases for each endpoint.

a. We will need to install testing framework like mocha and assertion library like chai and nyc for test coverage. From the terminal run:

npm install --save-dev mocha chai chai-http nyc

b. We will create a test folder in the path /*book-app/api/. *Then create the test file, call it test.js . Hence, the file is located: /book-app/api/test/test.js

import chai from 'chai';
import chatHttp from 'chai-http';
import 'chai/register-should';
import app from '../index';

chai.use(chatHttp);
const { expect } = chai;

describe('Testing the book endpoints:', () => {
  it('It should create a book', (done) => {
    const book = {
      title: 'First Awesome book',
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(201);
        expect(res.body.data).to.include({
          id: 1,
          title: book.title,
          price: book.price,
          description: book.description
        });
        done();
      });
  });

  it('It should not create a book with incomplete parameters', (done) => {
    const book = {
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        done();
      });
  });

  it('It should get all books', (done) => {
    chai.request(app)
      .get('/api/v1/books')
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data[0].should.have.property('id');
        res.body.data[0].should.have.property('title');
        res.body.data[0].should.have.property('price');
        res.body.data[0].should.have.property('description');
        done();
      });
  });

  it('It should get a particular book', (done) => {
    const bookId = 1;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data.should.have.property('id');
        res.body.data.should.have.property('title');
        res.body.data.should.have.property('price');
        res.body.data.should.have.property('description');
        done();
      });
  });

  it('It should not get a particular book with invalid id', (done) => {
    const bookId = 8888;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id ${bookId}`);
        done();
      });
  });

  it('It should not get a particular book with non-numeric id', (done) => {
    const bookId = 'aaa';
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });

  it('It should update a book', (done) => {
    const bookId = 1;
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book',
      price: 'import chai from 'chai';
import chatHttp from 'chai-http';
import 'chai/register-should';
import app from '../index';

chai.use(chatHttp);
const { expect } = chai;

describe('Testing the book endpoints:', () => {
  it('It should create a book', (done) => {
    const book = {
      title: 'First Awesome book',
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(201);
        expect(res.body.data).to.include({
          id: 1,
          title: book.title,
          price: book.price,
          description: book.description
        });
        done();
      });
  });

  it('It should not create a book with incomplete parameters', (done) => {
    const book = {
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        done();
      });
  });

  it('It should get all books', (done) => {
    chai.request(app)
      .get('/api/v1/books')
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data[0].should.have.property('id');
        res.body.data[0].should.have.property('title');
        res.body.data[0].should.have.property('price');
        res.body.data[0].should.have.property('description');
        done();
      });
  });

  it('It should get a particular book', (done) => {
    const bookId = 1;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data.should.have.property('id');
        res.body.data.should.have.property('title');
        res.body.data.should.have.property('price');
        res.body.data.should.have.property('description');
        done();
      });
  });

  it('It should not get a particular book with invalid id', (done) => {
    const bookId = 8888;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id ${bookId}`);
        done();
      });
  });

  it('It should not get a particular book with non-numeric id', (done) => {
    const bookId = 'aaa';
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });

  it('It should update a book', (done) => {
    const bookId = 1;
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book',
      price: '$10.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data.id).equal(updatedBook.id);
        expect(res.body.data.title).equal(updatedBook.title);
        expect(res.body.data.price).equal(updatedBook.price);
        expect(res.body.data.description).equal(updatedBook.description);
        done();
      });
  });

  it('It should not update a book with invalid id', (done) => {
    const bookId = '9999';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id: ${bookId}`);
        done();
      });
  });

  it('It should not update a book with non-numeric id value', (done) => {
    const bookId = 'ggg';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });


  it('It should delete a book', (done) => {
    const bookId = 1;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data).to.include({});
        done();
      });
  });

  it('It should not delete a book with invalid id', (done) => {
    const bookId = 777;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Book with the id ${bookId} cannot be found`);
        done();
      });
  });

  it('It should not delete a book with non-numeric id', (done) => {
    const bookId = 'bbb';
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message').eql('Please provide a numeric value');
        done();
      });
  });
});
0.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data.id).equal(updatedBook.id);
        expect(res.body.data.title).equal(updatedBook.title);
        expect(res.body.data.price).equal(updatedBook.price);
        expect(res.body.data.description).equal(updatedBook.description);
        done();
      });
  });

  it('It should not update a book with invalid id', (done) => {
    const bookId = '9999';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: 'import chai from 'chai';
import chatHttp from 'chai-http';
import 'chai/register-should';
import app from '../index';

chai.use(chatHttp);
const { expect } = chai;

describe('Testing the book endpoints:', () => {
  it('It should create a book', (done) => {
    const book = {
      title: 'First Awesome book',
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(201);
        expect(res.body.data).to.include({
          id: 1,
          title: book.title,
          price: book.price,
          description: book.description
        });
        done();
      });
  });

  it('It should not create a book with incomplete parameters', (done) => {
    const book = {
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        done();
      });
  });

  it('It should get all books', (done) => {
    chai.request(app)
      .get('/api/v1/books')
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data[0].should.have.property('id');
        res.body.data[0].should.have.property('title');
        res.body.data[0].should.have.property('price');
        res.body.data[0].should.have.property('description');
        done();
      });
  });

  it('It should get a particular book', (done) => {
    const bookId = 1;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data.should.have.property('id');
        res.body.data.should.have.property('title');
        res.body.data.should.have.property('price');
        res.body.data.should.have.property('description');
        done();
      });
  });

  it('It should not get a particular book with invalid id', (done) => {
    const bookId = 8888;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id ${bookId}`);
        done();
      });
  });

  it('It should not get a particular book with non-numeric id', (done) => {
    const bookId = 'aaa';
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });

  it('It should update a book', (done) => {
    const bookId = 1;
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book',
      price: '$10.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data.id).equal(updatedBook.id);
        expect(res.body.data.title).equal(updatedBook.title);
        expect(res.body.data.price).equal(updatedBook.price);
        expect(res.body.data.description).equal(updatedBook.description);
        done();
      });
  });

  it('It should not update a book with invalid id', (done) => {
    const bookId = '9999';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id: ${bookId}`);
        done();
      });
  });

  it('It should not update a book with non-numeric id value', (done) => {
    const bookId = 'ggg';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });


  it('It should delete a book', (done) => {
    const bookId = 1;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data).to.include({});
        done();
      });
  });

  it('It should not delete a book with invalid id', (done) => {
    const bookId = 777;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Book with the id ${bookId} cannot be found`);
        done();
      });
  });

  it('It should not delete a book with non-numeric id', (done) => {
    const bookId = 'bbb';
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message').eql('Please provide a numeric value');
        done();
      });
  });
});
1.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id: ${bookId}`);
        done();
      });
  });

  it('It should not update a book with non-numeric id value', (done) => {
    const bookId = 'ggg';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: 'import chai from 'chai';
import chatHttp from 'chai-http';
import 'chai/register-should';
import app from '../index';

chai.use(chatHttp);
const { expect } = chai;

describe('Testing the book endpoints:', () => {
  it('It should create a book', (done) => {
    const book = {
      title: 'First Awesome book',
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(201);
        expect(res.body.data).to.include({
          id: 1,
          title: book.title,
          price: book.price,
          description: book.description
        });
        done();
      });
  });

  it('It should not create a book with incomplete parameters', (done) => {
    const book = {
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        done();
      });
  });

  it('It should get all books', (done) => {
    chai.request(app)
      .get('/api/v1/books')
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data[0].should.have.property('id');
        res.body.data[0].should.have.property('title');
        res.body.data[0].should.have.property('price');
        res.body.data[0].should.have.property('description');
        done();
      });
  });

  it('It should get a particular book', (done) => {
    const bookId = 1;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data.should.have.property('id');
        res.body.data.should.have.property('title');
        res.body.data.should.have.property('price');
        res.body.data.should.have.property('description');
        done();
      });
  });

  it('It should not get a particular book with invalid id', (done) => {
    const bookId = 8888;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id ${bookId}`);
        done();
      });
  });

  it('It should not get a particular book with non-numeric id', (done) => {
    const bookId = 'aaa';
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });

  it('It should update a book', (done) => {
    const bookId = 1;
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book',
      price: '$10.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data.id).equal(updatedBook.id);
        expect(res.body.data.title).equal(updatedBook.title);
        expect(res.body.data.price).equal(updatedBook.price);
        expect(res.body.data.description).equal(updatedBook.description);
        done();
      });
  });

  it('It should not update a book with invalid id', (done) => {
    const bookId = '9999';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id: ${bookId}`);
        done();
      });
  });

  it('It should not update a book with non-numeric id value', (done) => {
    const bookId = 'ggg';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });


  it('It should delete a book', (done) => {
    const bookId = 1;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data).to.include({});
        done();
      });
  });

  it('It should not delete a book with invalid id', (done) => {
    const bookId = 777;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Book with the id ${bookId} cannot be found`);
        done();
      });
  });

  it('It should not delete a book with non-numeric id', (done) => {
    const bookId = 'bbb';
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message').eql('Please provide a numeric value');
        done();
      });
  });
});
1.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });


  it('It should delete a book', (done) => {
    const bookId = 1;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data).to.include({});
        done();
      });
  });

  it('It should not delete a book with invalid id', (done) => {
    const bookId = 777;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Book with the id ${bookId} cannot be found`);
        done();
      });
  });

  it('It should not delete a book with non-numeric id', (done) => {
    const bookId = 'bbb';
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message').eql('Please provide a numeric value');
        done();
      });
  });
});

c. Include the test script in package.json file

Replace:

"test": "echo \"Error: no test specified\" && exit 1"

With:

"test": "export NODE_ENV=test &&  sequelize db:migrate:undo:all  && sequelize db:migrate  && nyc --require @babel/register  mocha ./api/test/test.js --timeout 20000 --exit"

Observe this:

export NODE_ENV=test   //Works for mac OS

Using Windows, do:

SET NODE_ENV=test  //works for windows

Remember, we have a test database we created earlier: book_test So, from the test script, we run migrate afresh each time.

Before you run the test, ensure that PostgreSQL server is running.

Save all files and run the test:

npm run test

A Sample output:

All test cases passing!

Step 9

Integrate Travis CI, Coveralls and Code Climate

This i presume, you have been waiting for.

Ensure that all test cases are passing, because Travis will also run those tests. So if any is breaking in your local, it will also break in Travis.

Before we proceed, let’s compile all we have and put them in one folder called build in this folder all ES6 is converted to ES5 by babel .

Include the script immediately after the test script in package.json

"build": "rm -rf ./build && babel -d ./build ./api -s",

We should also include scripts for coveralls and code-climate

"generate-lcov": "nyc report --reporter=text-lcov > lcov.info",
"coveralls-coverage": "coveralls < lcov.info",
"codeclimate-coverage": "codeclimate-test-reporter < lcov.info",
"coverage": "nyc npm test && npm run generate-lcov && npm run coveralls-coverage && npm run codeclimate-coverage"

The script should look like:

"scripts": {
"dev": "nodemon --exec babel-node ./api/index.js",
"test": "export NODE_ENV=test &&  sequelize db:migrate:undo:all  && sequelize db:migrate  && nyc --require @babel/register  mocha ./api/test/test.js --timeout 20000 --exit",
"build": "rm -rf ./build && babel -d ./build ./api -s",
"generate-lcov": "nyc report --reporter=text-lcov > lcov.info",
"coveralls-coverage": "coveralls < lcov.info",
"codeclimate-coverage": "codeclimate-test-reporter < lcov.info",
"coverage": "nyc npm test && npm run generate-lcov && npm run coveralls-coverage && npm run codeclimate-coverage"
},

For this project, the final look of your package.json file should be:

{
  "name": "book-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon --exec babel-node ./api/index.js",
    "test": "export NODE_ENV=test &&  sequelize db:migrate:undo:all  && sequelize db:migrate  && nyc --require @babel/register  mocha ./api/test/test.js --timeout 20000 --exit",
    "build": "rm -rf ./build && babel -d ./build ./api -s",
    "generate-lcov": "nyc report --reporter=text-lcov > lcov.info",
    "coveralls-coverage": "coveralls < lcov.info",
    "codeclimate-coverage": "codeclimate-test-reporter < lcov.info",
    "coverage": "nyc npm test && npm run generate-lcov && npm run coveralls-coverage && npm run codeclimate-coverage"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "chai": "^4.2.0",
    "chai-http": "^4.2.1",
    "dotenv": "^7.0.0",
    "express": "^4.16.4",
    "nodemon": "^1.18.11",
    "path": "^0.12.7",
    "pg": "^7.10.0",
    "pg-hstore": "^2.3.2",
    "sequelize": "^5.7.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.4.3",
    "@babel/core": "^7.4.3",
    "@babel/node": "^7.2.2",
    "@babel/plugin-transform-runtime": "^7.4.3",
    "@babel/preset-env": "^7.4.3",
    "@babel/register": "^7.4.0",
    "@babel/runtime": "^7.4.3",
    "babel-loader": "^8.0.5",
    "codeclimate-test-reporter": "^0.5.1",
    "coveralls": "^3.0.2",
    "eslint": "^5.16.0",
    "eslint-config-airbnb-base": "^13.1.0",
    "eslint-plugin-import": "^2.17.2",
    "mocha": "^6.1.4",
    "nyc": "^13.3.0"
  }
}

Now let’s create the build folder by running:

npm run build

You will see a folder in the path: /book-app/

book-app
├── api
├── build

a. Sign-Up/Sign-In with Travis

Create an account with Travis if you don’t have one already;

**b. **Create a .travis.yml file. This is the file Travis will look for and execute commands. This file should be created in the same path as the package.jsonThat is: /book-app/

Populate the file with:

language: node_js
node_js:
  - "stable"
cache:
  directories:
    - "node_modules"
install:
  - npm install
services:
  - postgresql

env:
  global:
  - NODE_ENV=test

before_script:
  - psql -c 'create database book_test;' -U postgres
  - psql -c "CREATE USER steven WITH PASSWORD null;" -U postgres
  - npm run build
  - npm install -g sequelize-cli
  - sequelize db:migrate
script:
  - npm test
after_success:
  - npm run coverage


Observe that there is a script to create a database, a user , run migrationrun build npm run build. Also observe the test command npm test

c. Push your code to github:

To see the workings of Travis, Coveralls and Code Climate, push the code you have been working on to a new git repository or an existing one created for this project.

After pushing to github, go to your Travis account and turn on that repository:

An example:

Click on the repository, It will take to a page like this:

You may likely see this badge first:

travis_unknown_build

If your build does not start automatically, look at the top right of the screenshot above, you will see More options choose the Trigger build , then a modal pops up, click the Trigger custom build . This will start the build manually.

A mail will be sent to you when the build is completed. You can check the build status again, you should see the green passing badge.

d. Use the Travis badge in your github repository

Click on the Travis badge, a modal pops up, Choose markdown and copy the link and paste in the README.md file of your repository

e. Create an account with or sign-in to your Coveralls

Connect the same repository we used for Travis by turning it on. Then click on DETAILS. Scroll down, copy the badge code when you click EMBED and add it to your README.md file

f. Create an account with or sign-in to your CodeClimate

Once you are in, Add the same repository you have used in the two cases above.

Once you click on the repository, it will take you to a page similar to this:

Code maintainability can have status A to F

The A status shows that the code can be maintained easily, while a status of Ftells the opposite.

To get the badge code, click on the Repo Settings tab. Click on the Badges. click the Markdown, copy the code and add it to your README.md file

Note:

Let me bring to your notice that Code Climate also have Code Coverage. Since Coveralls is already covering our code, i didn’t see it necessary to add Code Coverage. If you wish to add it, Click on Test Coverage and follow the instructions.

So, Your README.md should look similar to:

[![Build Status](https://travis-ci.org/victorsteven/Book-app-NodeJS-PostgreSQL-Travis-Coveralls-Code-Climate.svg?branch=master)](https://travis-ci.org/victorsteven/Book-app-NodeJS-PostgreSQL-Travis-Coveralls-Code-Climate)    
[![Coverage Status (https://coveralls.io/repos/github/victorsteven/Book-app-NodeJS-PostgreSQL-Travis-Coveralls-Code-Climate/badge.svg?branch=master)](https://coveralls.io/github/victorsteven/Book-app-NodeJS-PostgreSQL-Travis-Coveralls-Code-Climate?branch=master)    
[![Maintainability](https://api.codeclimate.com/v1/badges/750e4ce5c8a8112eec3a/maintainability)](https://codeclimate.com/github/victorsteven/Book-app-NodeJS-PostgreSQL-Travis-Coveralls-Code-Climate/maintainability)

With the output:

Bravo!

Step 10:

Final testing and scaling the api

Wow! This article is about 12 minutes read. I admire your patience to see the very end. However, I can’t call this the end because, there are still some stuffs to do, which, you wont have issues executing i guess.

a. You can host the application on <a href="https://heroku.com/" target="_blank">Heroku</a>

b. You can create more endpoints

c. You can write more test cases

d. And lots more.

Conclusion

I hope you didn’t have too much trouble following the instructions in this article. This article is very basic, meaning that you can apply the knowledge gained here to any similar project you are currently working on.

Get the source code here: github

Thanks for reading ❤

#node-js #express #postgresql

What is GEEK

Buddha Community

Restful API with NodeJS, Express, PostgreSQL, Sequelize, Travis, Mocha, Coveralls and Code Climate
Chaz  Homenick

Chaz Homenick

1602725748

Why You Should Consider Low-Code Approach to Building a REST API

APIs have been around for decades – they allow different systems to talk to each other in a seamless, fast fashion – yet it’s been during the past decade that this technology has become a significant force.

So then why all the interest in APIs? We all know the usual stories – Uber, Airbnb, Apple Pay… the list goes on, and the reasons are plentiful. Today the question is, how? Perhaps you are looking to differentiate your business or want a first-mover advantage.  How can you execute quickly and at low cost/risk to try new market offerings?

An API provides several benefits to an organisation, but without a dedicated team of trained developers, it might seem like an implausible option. Developers are expensive, and it can take months to develop an API from the ground up. If you don’t fancy outsourcing or have the capability in house to build internal APIs, a low-code platform might just be the answer.

Before You Begin: Plan long-term, start small.

For a small one-page application, this might only be a day or two of talking with stakeholders and designing business logic. The purpose of this first step is to ensure that the API will cover all use cases and provides stakeholders with what they need. Refactoring an entire coding design due to missing business logic is not only frustrating for the development team but adds high cost and time to the API project.

During the planning and design stage, remember that running an API requires more infrastructure than just resources to execute endpoint logic. You need a database to store the data, an email system to send messages, storage for files, and security to handle authorisation and authentication. These services can be farmed out to cloud providers to expedite the API build process (e.g. AWS provides all these infrastructure components, but Microsoft Azure is an optional cloud provider with SendGrid as the email application.)

**Planning considerations: **An API “speaks” in JSON or XML, so the output provided to client applications should be decided. Should you choose to later create endpoints for public developer consumption, you could offer both for ease-of-use and fostering more adoption. Ensuring the API follows OpenAPI standards will encourage more adoption and attract more developers.

#api #rest-api #api-development #restful-api #low-code-platform #low-code #build-a-rest-api #low-code-approach

Wilford  Pagac

Wilford Pagac

1594289280

What is REST API? An Overview | Liquid Web

What is REST?

The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

REST was initially defined in a dissertation by Roy Fielding’s twenty years ago. He proposed these standards as an alternative to SOAP (The Simple Object Access Protocol is a simple standard for accessing objects and exchanging structured messages within a distributed computing environment). REST (or RESTful) defines the general rules used to regulate the interactions between web apps utilizing the HTTP protocol for CRUD (create, retrieve, update, delete) operations.

What is an API?

An API (or Application Programming Interface) provides a method of interaction between two systems.

What is a RESTful API?

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format.

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

When using a RESTful API, we should determine in advance what resources we want to expose to the outside world. Typically, the RESTful API service is implemented, keeping the following ideas in mind:

  • Format: There should be no restrictions on the data exchange format
  • Implementation: REST is based entirely on HTTP
  • Service Definition: Because REST is very flexible, API can be modified to ensure the application understands the request/response format.
  • The RESTful API focuses on resources and how efficiently you perform operations with it using HTTP.

The features of the REST API design style state:

  • Each entity must have a unique identifier.
  • Standard methods should be used to read and modify data.
  • It should provide support for different types of resources.
  • The interactions should be stateless.

For REST to fit this model, we must adhere to the following rules:

  • Client-Server Architecture: The interface is separate from the server-side data repository. This affords flexibility and the development of components independently of each other.
  • Detachment: The client connections are not stored on the server between requests.
  • Cacheability: It must be explicitly stated whether the client can store responses.
  • Multi-level: The API should work whether it interacts directly with a server or through an additional layer, like a load balancer.

#tutorials #api #application #application programming interface #crud #http #json #programming #protocols #representational state transfer #rest #rest api #rest api graphql #rest api json #rest api xml #restful #soap #xml #yaml

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Billy Chandler

Billy Chandler

1559619853

Restful API with NodeJS, Express, PostgreSQL, Sequelize, Travis, Mocha, Coveralls and Code Climate

NodeJS is becoming a backend language of choice for many developers.

In this article, I am going to work you through building a Simple Restful API with:

  • NodeJS — For writing Javascript server-side applications
  • Express — A NodeJS framework
  • PostgreSQL — An open source object-relational database
  • Sequelize — An ORM(Object Relational Mapping) of PostreSQL
  • Travis —A continuous integration service for Testing Applications
  • Coveralls — **A **web service to help you track your code coverage over time.
  • Code Climate — Provides automated code review for maintainability and test coverage.
  • Babel — To convert ES6 javascript code to ES5

Though overwhelming, but you learn how to use these technologies simultaneously.

Let’s Build This!

This project is going to be built from scratch, without webpack, browserify or Gulp.

Step 1:

Setting Environment and Installing Dependencies:

a. Create a new directory called **book-app **and switch to that directory

mkdir book-app
cd book-app

b. Initialise npm and follow the instructions

npm init -y

c. Install Express and Body-parser:

npm install --save express body-parser

d. Install babel: Because we need to convert our ES6 code to ES5. Install babel dependencies by copying the code below and paste in the terminal of the working directory:

npm install --save-dev @babel/core @babel/cli @babel/node @babel/plugin-transform-runtime @babel/preset-env @babel/register @babel/runtime babel-loader

Create the .babelrc file in the path: /book-app/ and populate it with*:*

{
   "presets": ["@babel/preset-env"],
   "plugins": [["@babel/transform-runtime"]]
}

e. Install eslint and airbnb style guide. This is Optional!

This will help you format your code in an easy to read state.

npm install --save-dev eslint eslint-config-airbnb-base eslint-plugin-import

Create a file .eslintrc.js in the path: /book-app/

This the way i configured mine:

module.exports = {
  "extends": "airbnb-base",
"rules": {
"no-console": 0,
"no-param-reassign": [2, {"props": false}],
"prefer-destructuring": 0,
"treatUndefinedAsUnspecified": true,
"arrow-body-style": 0,
"comma-dangle": 0,
},
"env": {
"commonjs": true,
"node": true,
"mocha": true
},
};

Of course, you can setup yours however you wish.

f. Install nodemon:

In the cause of this tutorial, we will need to run node server over and over again. Nodemon is like a watcher that automatically restarts the server each time changes are made. You can install it globally using:

npm install -g nodemon

Note that this installation will not be in this project package.json file, because it was installed globally.

g. Including nodemon in the package.json file:

Open the package.json file, edit the scripts object as follows:

"scripts": {
  "dev": "nodemon --exec babel-node ./api/index.js",
  "test": "echo \"Error: no test specified\" && exit 1"
}

Observe the** ./api/index.js** ? Don’t worry, we will create the file in step 2.

At this point, your package.json file should look like this:

{
"name": "book-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon --exec babel-node ./api/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
  "body-parser": "^1.18.3",
  "express": "^4.16.4"
},
"devDependencies": {
  "@babel/cli": "^7.4.3",
  "@babel/core": "^7.4.3",
  "@babel/node": "^7.2.2",
  "@babel/plugin-transform-runtime": "^7.4.3",
  "@babel/preset-env": "^7.4.3",
  "@babel/register": "^7.4.0",
  "@babel/runtime": "^7.4.3",
  "babel-loader": "^8.0.5"
  }
}

h. Structuring the application:

Create a directory called api . Then create the index.js file, which is the root file for this application. You should be in the path: book-app/api/

touch index.js

Change to the api directory and create another directory called server. Your directory tree should now look like this:

book-app
├── api
│   ├── server
├── ├── index.js
├── node_modules
├── package.json
└── package-lock.json

Step 2:

Edit the index.js file and start the server

a. Edit the index.js file:

import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const port = process.env.PORT || 8000;
// when a random route is inputed
app.get('*', (req, res) => res.status(200).send({
   message: 'Welcome to this API.'
}));
app.listen(port, () => {
   console.log(`Server is running on PORT ${port}`);
});
export default app;

b. Start the server

Since we have defined the script to start the server, we simply run in the terminal from the path: /book-app/api/:

npm run dev

Hopefully you will see nodemon running in the terminal, with the port number the server is running on:

Step 3

Setup PostreSQL Database

a. Install:

If you don’t already have postreSQL running in your machine, you can download it and setup it.

If you are on a mac OS, you can follow this instruction: https://medium.com/@Umesh_Kafle/postgresql-and-postgis-installation-in-mac-os-87fa98a6814d

For Windows users: http://www.postgresqltutorial.com/install-postgresql/

For Ubuntu users: https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-18-04

**b. Setup: **You can use the default user called: postgres or you can create a new user. There is probably hundreds of materials out there that can help you achieve this.

If you have any issues installing and setting up postgreSQL on your local machine, you can use an online database such as ElephantSQL

Step 4

Setup Sequelize

Sequelize is an ORM(Object Relational Mapping) for PostgreSQL. What this means is that, instead of writing raw SQL queries, ORM is used instead, which makes work easier.

a. Install sequelize cli globally:

npm install -g sequelize-cli

Note, if you wish not to install this globally, you’ll need to prefix every call to the sequelize command with ./node_modules/.bin

b. Create the file: **.sequelizerc **in the path: /boook-app/. That is, outside of the api folder.

touch .sequelizerc

Write in the file, the code below

const path  = require('path')
module.exports = {
    "config": path.resolve('./api/server/src/config', 'config.js'),
    "models-path": path.resolve('./api/server/src/models'),
    "seeders-path": path.resolve('./api/server/src/seeders'),
    "migrations-path": path.resolve('./api/server/src/migrations')
};

Observe that we required path. Let’s quickly install it:

npm install --save path

c. Install postgreSQL and sequelize dependencies

npm install --save sequelize pg pg-hstore

Where: pg = postgreSQL and pg-hstore = converts data into the Postgres hstore format.

d. Initialize Sequelize:

This will generate the Sequelize boilerplate which includes, models, migrations and seeders. Run:

sequelize init

The directory tree should now resemble this:

book-app
├── api
│   └── index.js
│   ├── server
│   │   └── src
│   │       └── config
│   │       ├── └── config.js
│   │       └── migrations
│   │       └── models
│   │       ├── └── index.js
│   │       └── seeders│  
├── .babelrc
└── .eslintrc.js
└── .sequelizerc
└── package.json
└── package-lock.json

e. Edit the book-app/api/server/models/index.js file.

This is the current state:

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

We will use ES6 syntax.

So, book-app/api/server/models/index.js becomes:

f. Editing the config.js file:

Let’s quickly install dotenv package. This will make it easier when using .env variables

npm install --save dotenv

Now, the config.js file:

You can replace the username with the one you used while setting up your postgreSQL. If you don’t remember creating a username, It means you are using the default user, which is postgres . For the password if you created a user, use the password, else, leave it the way it is above.

Also, incase you are using an online database, such as ElephantSQL, uncomment this lines:

development: {
   use_env_variable: 'DATABASE_URL'
},

Then, you will export the database URL into your environment

export DATABASE_URL=our-database-url

where our-database-url is the URL we copied from ElephantSQL. Every time you need to run this application, you will need to export the DATABASE_URLfirst.

Remember, if you decide to use the online database, and have uncommented the line above, comment the development setup for the local PostgreSQL database. So as to avoid name duplication.

g. Create a .env file in the path: /book-app/.

DB_NAME=books
DB_USER=steven
DB_PASS=
DB_PORT=5432
DB_HOST=127.0.0.1
SECRET_KEY=any_secret

h. Use Database GUI(Graphical User Interface): Optional.

Instead of doing all database operations in the terminal, which is very painful for some, you can use a GUI such as pgadmin or tableplus

Step 5

Create Databases, Model and Migration

a. Create the Databases:

In the config.js file above, we referenced a database called books for development and book_test for testing. You can either use the GUI or Terminal to create these databases.

Before you run any command, ensure that the PostgreSQL server is running, on mac OS, run:

pg_ctl -D /usr/local/var/postgres start  //For mac OS
or:
brew services start postgresql    //To always run it on mac OS

pg_ctl -D "C:\Program Files\PostgreSQL\9.6\data" start 
//For Windows. Observe the 9.6, yours may be different

sudo service postgresql start //For Linux

Get the list of commands here.

Now, Creating the databases from the terminal:

createdb books
createdb book_test

b. Create the Model

We are creating just one model: book.js

sequelize model:create --name Book --attributes title:string, price:string, description:string

Locate** book.js** in the path: /book-app/api/server/src/models/

Using ES6 syntax and adding to the file, we have:

c. Refactor migration file

A migration file was also created when we ran that command to create the model, located in the path: …server/migrations/<date>-create-book.js

Edit the migration file to have:

Save all files and run migration:

sequelize db:migrate

You can check in the database to confirm if migration ran successfully.

Step 6

Create Services, Controllers, Routes and Utilities

Yes, we can put all the code in one file. But that is not best practice. So, is good we separate code into different files. We will create four folders in the path: /book-app/api/server:

book-app
├── api
    ├── server
        ├── controllers
        ├── routes
        ├── services
        ├── utils

a. Services:

You might ask, what is a Service? See it as a medium that helps us interface with our book model.

In the Services folder, create a file: BookService.js

b. Controllers

The Service file created above is used in our controller. Create a file called BookController.js in the controllers folder

This is the content:

c. Utilities

As seen, in the BookController.js file, we imported a file called Utils.js. This file contain all the responses we will assert for while running and testing the api endpoints.

Create the Utils.js file in the Utils folder.

Its content is:

d. Routes

Create the route file called BookRoutes.js in the routes folder.

Its content:

e. Editing the /book-app/api/index.js file to add the route file defined above:

Step 7

Running Endpoints

Time to see results!

We can test the endpoint using postman app or any API testing tool of your choice.

Start up the server, if you terminated it before:

npm run dev

If you dont know how to use postman, you might need to learn the basics, before continuing.

a. POST a book:

In the postman address bar enter this:

http://localhost:8000/api/v1/books    //POST

Change the http method to POST, then define the json data to post in the body

As an example:

b. GET all books

http://localhost:8000/api/v1/books    //GET

c. GET a particular book

http://localhost:8000/api/v1/books/:id    //GET

d. UPDATE a particular book

http://localhost:8000/api/v1/books/:id    //PUT

e. DELETE a particular book

http://localhost:8000/api/v1/books/:id    //DELETE

Step 8

Write Test Cases for Endpoints

I hope, all your endpoint worked as expected.

Now, let’s write test cases for each endpoint.

a. We will need to install testing framework like mocha and assertion library like chai and nyc for test coverage. From the terminal run:

npm install --save-dev mocha chai chai-http nyc

b. We will create a test folder in the path /*book-app/api/. *Then create the test file, call it test.js . Hence, the file is located: /book-app/api/test/test.js

import chai from 'chai';
import chatHttp from 'chai-http';
import 'chai/register-should';
import app from '../index';

chai.use(chatHttp);
const { expect } = chai;

describe('Testing the book endpoints:', () => {
  it('It should create a book', (done) => {
    const book = {
      title: 'First Awesome book',
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(201);
        expect(res.body.data).to.include({
          id: 1,
          title: book.title,
          price: book.price,
          description: book.description
        });
        done();
      });
  });

  it('It should not create a book with incomplete parameters', (done) => {
    const book = {
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        done();
      });
  });

  it('It should get all books', (done) => {
    chai.request(app)
      .get('/api/v1/books')
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data[0].should.have.property('id');
        res.body.data[0].should.have.property('title');
        res.body.data[0].should.have.property('price');
        res.body.data[0].should.have.property('description');
        done();
      });
  });

  it('It should get a particular book', (done) => {
    const bookId = 1;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data.should.have.property('id');
        res.body.data.should.have.property('title');
        res.body.data.should.have.property('price');
        res.body.data.should.have.property('description');
        done();
      });
  });

  it('It should not get a particular book with invalid id', (done) => {
    const bookId = 8888;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id ${bookId}`);
        done();
      });
  });

  it('It should not get a particular book with non-numeric id', (done) => {
    const bookId = 'aaa';
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });

  it('It should update a book', (done) => {
    const bookId = 1;
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book',
      price: 'import chai from 'chai';
import chatHttp from 'chai-http';
import 'chai/register-should';
import app from '../index';

chai.use(chatHttp);
const { expect } = chai;

describe('Testing the book endpoints:', () => {
  it('It should create a book', (done) => {
    const book = {
      title: 'First Awesome book',
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(201);
        expect(res.body.data).to.include({
          id: 1,
          title: book.title,
          price: book.price,
          description: book.description
        });
        done();
      });
  });

  it('It should not create a book with incomplete parameters', (done) => {
    const book = {
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        done();
      });
  });

  it('It should get all books', (done) => {
    chai.request(app)
      .get('/api/v1/books')
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data[0].should.have.property('id');
        res.body.data[0].should.have.property('title');
        res.body.data[0].should.have.property('price');
        res.body.data[0].should.have.property('description');
        done();
      });
  });

  it('It should get a particular book', (done) => {
    const bookId = 1;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data.should.have.property('id');
        res.body.data.should.have.property('title');
        res.body.data.should.have.property('price');
        res.body.data.should.have.property('description');
        done();
      });
  });

  it('It should not get a particular book with invalid id', (done) => {
    const bookId = 8888;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id ${bookId}`);
        done();
      });
  });

  it('It should not get a particular book with non-numeric id', (done) => {
    const bookId = 'aaa';
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });

  it('It should update a book', (done) => {
    const bookId = 1;
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book',
      price: '$10.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data.id).equal(updatedBook.id);
        expect(res.body.data.title).equal(updatedBook.title);
        expect(res.body.data.price).equal(updatedBook.price);
        expect(res.body.data.description).equal(updatedBook.description);
        done();
      });
  });

  it('It should not update a book with invalid id', (done) => {
    const bookId = '9999';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id: ${bookId}`);
        done();
      });
  });

  it('It should not update a book with non-numeric id value', (done) => {
    const bookId = 'ggg';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });


  it('It should delete a book', (done) => {
    const bookId = 1;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data).to.include({});
        done();
      });
  });

  it('It should not delete a book with invalid id', (done) => {
    const bookId = 777;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Book with the id ${bookId} cannot be found`);
        done();
      });
  });

  it('It should not delete a book with non-numeric id', (done) => {
    const bookId = 'bbb';
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message').eql('Please provide a numeric value');
        done();
      });
  });
});
0.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data.id).equal(updatedBook.id);
        expect(res.body.data.title).equal(updatedBook.title);
        expect(res.body.data.price).equal(updatedBook.price);
        expect(res.body.data.description).equal(updatedBook.description);
        done();
      });
  });

  it('It should not update a book with invalid id', (done) => {
    const bookId = '9999';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: 'import chai from 'chai';
import chatHttp from 'chai-http';
import 'chai/register-should';
import app from '../index';

chai.use(chatHttp);
const { expect } = chai;

describe('Testing the book endpoints:', () => {
  it('It should create a book', (done) => {
    const book = {
      title: 'First Awesome book',
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(201);
        expect(res.body.data).to.include({
          id: 1,
          title: book.title,
          price: book.price,
          description: book.description
        });
        done();
      });
  });

  it('It should not create a book with incomplete parameters', (done) => {
    const book = {
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        done();
      });
  });

  it('It should get all books', (done) => {
    chai.request(app)
      .get('/api/v1/books')
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data[0].should.have.property('id');
        res.body.data[0].should.have.property('title');
        res.body.data[0].should.have.property('price');
        res.body.data[0].should.have.property('description');
        done();
      });
  });

  it('It should get a particular book', (done) => {
    const bookId = 1;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data.should.have.property('id');
        res.body.data.should.have.property('title');
        res.body.data.should.have.property('price');
        res.body.data.should.have.property('description');
        done();
      });
  });

  it('It should not get a particular book with invalid id', (done) => {
    const bookId = 8888;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id ${bookId}`);
        done();
      });
  });

  it('It should not get a particular book with non-numeric id', (done) => {
    const bookId = 'aaa';
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });

  it('It should update a book', (done) => {
    const bookId = 1;
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book',
      price: '$10.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data.id).equal(updatedBook.id);
        expect(res.body.data.title).equal(updatedBook.title);
        expect(res.body.data.price).equal(updatedBook.price);
        expect(res.body.data.description).equal(updatedBook.description);
        done();
      });
  });

  it('It should not update a book with invalid id', (done) => {
    const bookId = '9999';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id: ${bookId}`);
        done();
      });
  });

  it('It should not update a book with non-numeric id value', (done) => {
    const bookId = 'ggg';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });


  it('It should delete a book', (done) => {
    const bookId = 1;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data).to.include({});
        done();
      });
  });

  it('It should not delete a book with invalid id', (done) => {
    const bookId = 777;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Book with the id ${bookId} cannot be found`);
        done();
      });
  });

  it('It should not delete a book with non-numeric id', (done) => {
    const bookId = 'bbb';
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message').eql('Please provide a numeric value');
        done();
      });
  });
});
1.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id: ${bookId}`);
        done();
      });
  });

  it('It should not update a book with non-numeric id value', (done) => {
    const bookId = 'ggg';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: 'import chai from 'chai';
import chatHttp from 'chai-http';
import 'chai/register-should';
import app from '../index';

chai.use(chatHttp);
const { expect } = chai;

describe('Testing the book endpoints:', () => {
  it('It should create a book', (done) => {
    const book = {
      title: 'First Awesome book',
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(201);
        expect(res.body.data).to.include({
          id: 1,
          title: book.title,
          price: book.price,
          description: book.description
        });
        done();
      });
  });

  it('It should not create a book with incomplete parameters', (done) => {
    const book = {
      price: '$9.99',
      description: 'This is the awesome book'
    };
    chai.request(app)
      .post('/api/v1/books')
      .set('Accept', 'application/json')
      .send(book)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        done();
      });
  });

  it('It should get all books', (done) => {
    chai.request(app)
      .get('/api/v1/books')
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data[0].should.have.property('id');
        res.body.data[0].should.have.property('title');
        res.body.data[0].should.have.property('price');
        res.body.data[0].should.have.property('description');
        done();
      });
  });

  it('It should get a particular book', (done) => {
    const bookId = 1;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        res.body.data.should.have.property('id');
        res.body.data.should.have.property('title');
        res.body.data.should.have.property('price');
        res.body.data.should.have.property('description');
        done();
      });
  });

  it('It should not get a particular book with invalid id', (done) => {
    const bookId = 8888;
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id ${bookId}`);
        done();
      });
  });

  it('It should not get a particular book with non-numeric id', (done) => {
    const bookId = 'aaa';
    chai.request(app)
      .get(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });

  it('It should update a book', (done) => {
    const bookId = 1;
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book',
      price: '$10.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data.id).equal(updatedBook.id);
        expect(res.body.data.title).equal(updatedBook.title);
        expect(res.body.data.price).equal(updatedBook.price);
        expect(res.body.data.description).equal(updatedBook.description);
        done();
      });
  });

  it('It should not update a book with invalid id', (done) => {
    const bookId = '9999';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Cannot find book with the id: ${bookId}`);
        done();
      });
  });

  it('It should not update a book with non-numeric id value', (done) => {
    const bookId = 'ggg';
    const updatedBook = {
      id: bookId,
      title: 'Updated Awesome book again',
      price: '$11.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });


  it('It should delete a book', (done) => {
    const bookId = 1;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data).to.include({});
        done();
      });
  });

  it('It should not delete a book with invalid id', (done) => {
    const bookId = 777;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Book with the id ${bookId} cannot be found`);
        done();
      });
  });

  it('It should not delete a book with non-numeric id', (done) => {
    const bookId = 'bbb';
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message').eql('Please provide a numeric value');
        done();
      });
  });
});
1.99',
      description: 'We have updated the price'
    };
    chai.request(app)
      .put(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .send(updatedBook)
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message')
                            .eql('Please input a valid numeric value');
        done();
      });
  });


  it('It should delete a book', (done) => {
    const bookId = 1;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data).to.include({});
        done();
      });
  });

  it('It should not delete a book with invalid id', (done) => {
    const bookId = 777;
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(404);
        res.body.should.have.property('message')
                            .eql(`Book with the id ${bookId} cannot be found`);
        done();
      });
  });

  it('It should not delete a book with non-numeric id', (done) => {
    const bookId = 'bbb';
    chai.request(app)
      .delete(`/api/v1/books/${bookId}`)
      .set('Accept', 'application/json')
      .end((err, res) => {
        expect(res.status).to.equal(400);
        res.body.should.have.property('message').eql('Please provide a numeric value');
        done();
      });
  });
});

c. Include the test script in package.json file

Replace:

"test": "echo \"Error: no test specified\" && exit 1"

With:

"test": "export NODE_ENV=test &&  sequelize db:migrate:undo:all  && sequelize db:migrate  && nyc --require @babel/register  mocha ./api/test/test.js --timeout 20000 --exit"

Observe this:

export NODE_ENV=test   //Works for mac OS

Using Windows, do:

SET NODE_ENV=test  //works for windows

Remember, we have a test database we created earlier: book_test So, from the test script, we run migrate afresh each time.

Before you run the test, ensure that PostgreSQL server is running.

Save all files and run the test:

npm run test

A Sample output:

All test cases passing!

Step 9

Integrate Travis CI, Coveralls and Code Climate

This i presume, you have been waiting for.

Ensure that all test cases are passing, because Travis will also run those tests. So if any is breaking in your local, it will also break in Travis.

Before we proceed, let’s compile all we have and put them in one folder called build in this folder all ES6 is converted to ES5 by babel .

Include the script immediately after the test script in package.json

"build": "rm -rf ./build && babel -d ./build ./api -s",

We should also include scripts for coveralls and code-climate

"generate-lcov": "nyc report --reporter=text-lcov > lcov.info",
"coveralls-coverage": "coveralls < lcov.info",
"codeclimate-coverage": "codeclimate-test-reporter < lcov.info",
"coverage": "nyc npm test && npm run generate-lcov && npm run coveralls-coverage && npm run codeclimate-coverage"

The script should look like:

"scripts": {
"dev": "nodemon --exec babel-node ./api/index.js",
"test": "export NODE_ENV=test &&  sequelize db:migrate:undo:all  && sequelize db:migrate  && nyc --require @babel/register  mocha ./api/test/test.js --timeout 20000 --exit",
"build": "rm -rf ./build && babel -d ./build ./api -s",
"generate-lcov": "nyc report --reporter=text-lcov > lcov.info",
"coveralls-coverage": "coveralls < lcov.info",
"codeclimate-coverage": "codeclimate-test-reporter < lcov.info",
"coverage": "nyc npm test && npm run generate-lcov && npm run coveralls-coverage && npm run codeclimate-coverage"
},

For this project, the final look of your package.json file should be:

{
  "name": "book-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon --exec babel-node ./api/index.js",
    "test": "export NODE_ENV=test &&  sequelize db:migrate:undo:all  && sequelize db:migrate  && nyc --require @babel/register  mocha ./api/test/test.js --timeout 20000 --exit",
    "build": "rm -rf ./build && babel -d ./build ./api -s",
    "generate-lcov": "nyc report --reporter=text-lcov > lcov.info",
    "coveralls-coverage": "coveralls < lcov.info",
    "codeclimate-coverage": "codeclimate-test-reporter < lcov.info",
    "coverage": "nyc npm test && npm run generate-lcov && npm run coveralls-coverage && npm run codeclimate-coverage"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "chai": "^4.2.0",
    "chai-http": "^4.2.1",
    "dotenv": "^7.0.0",
    "express": "^4.16.4",
    "nodemon": "^1.18.11",
    "path": "^0.12.7",
    "pg": "^7.10.0",
    "pg-hstore": "^2.3.2",
    "sequelize": "^5.7.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.4.3",
    "@babel/core": "^7.4.3",
    "@babel/node": "^7.2.2",
    "@babel/plugin-transform-runtime": "^7.4.3",
    "@babel/preset-env": "^7.4.3",
    "@babel/register": "^7.4.0",
    "@babel/runtime": "^7.4.3",
    "babel-loader": "^8.0.5",
    "codeclimate-test-reporter": "^0.5.1",
    "coveralls": "^3.0.2",
    "eslint": "^5.16.0",
    "eslint-config-airbnb-base": "^13.1.0",
    "eslint-plugin-import": "^2.17.2",
    "mocha": "^6.1.4",
    "nyc": "^13.3.0"
  }
}

Now let’s create the build folder by running:

npm run build

You will see a folder in the path: /book-app/

book-app
├── api
├── build

a. Sign-Up/Sign-In with Travis

Create an account with Travis if you don’t have one already;

**b. **Create a .travis.yml file. This is the file Travis will look for and execute commands. This file should be created in the same path as the package.jsonThat is: /book-app/

Populate the file with:

language: node_js
node_js:
  - "stable"
cache:
  directories:
    - "node_modules"
install:
  - npm install
services:
  - postgresql

env:
  global:
  - NODE_ENV=test

before_script:
  - psql -c 'create database book_test;' -U postgres
  - psql -c "CREATE USER steven WITH PASSWORD null;" -U postgres
  - npm run build
  - npm install -g sequelize-cli
  - sequelize db:migrate
script:
  - npm test
after_success:
  - npm run coverage


Observe that there is a script to create a database, a user , run migrationrun build npm run build. Also observe the test command npm test

c. Push your code to github:

To see the workings of Travis, Coveralls and Code Climate, push the code you have been working on to a new git repository or an existing one created for this project.

After pushing to github, go to your Travis account and turn on that repository:

An example:

Click on the repository, It will take to a page like this:

You may likely see this badge first:

travis_unknown_build

If your build does not start automatically, look at the top right of the screenshot above, you will see More options choose the Trigger build , then a modal pops up, click the Trigger custom build . This will start the build manually.

A mail will be sent to you when the build is completed. You can check the build status again, you should see the green passing badge.

d. Use the Travis badge in your github repository

Click on the Travis badge, a modal pops up, Choose markdown and copy the link and paste in the README.md file of your repository

e. Create an account with or sign-in to your Coveralls

Connect the same repository we used for Travis by turning it on. Then click on DETAILS. Scroll down, copy the badge code when you click EMBED and add it to your README.md file

f. Create an account with or sign-in to your CodeClimate

Once you are in, Add the same repository you have used in the two cases above.

Once you click on the repository, it will take you to a page similar to this:

Code maintainability can have status A to F

The A status shows that the code can be maintained easily, while a status of Ftells the opposite.

To get the badge code, click on the Repo Settings tab. Click on the Badges. click the Markdown, copy the code and add it to your README.md file

Note:

Let me bring to your notice that Code Climate also have Code Coverage. Since Coveralls is already covering our code, i didn’t see it necessary to add Code Coverage. If you wish to add it, Click on Test Coverage and follow the instructions.

So, Your README.md should look similar to:

[![Build Status](https://travis-ci.org/victorsteven/Book-app-NodeJS-PostgreSQL-Travis-Coveralls-Code-Climate.svg?branch=master)](https://travis-ci.org/victorsteven/Book-app-NodeJS-PostgreSQL-Travis-Coveralls-Code-Climate)    
[![Coverage Status (https://coveralls.io/repos/github/victorsteven/Book-app-NodeJS-PostgreSQL-Travis-Coveralls-Code-Climate/badge.svg?branch=master)](https://coveralls.io/github/victorsteven/Book-app-NodeJS-PostgreSQL-Travis-Coveralls-Code-Climate?branch=master)    
[![Maintainability](https://api.codeclimate.com/v1/badges/750e4ce5c8a8112eec3a/maintainability)](https://codeclimate.com/github/victorsteven/Book-app-NodeJS-PostgreSQL-Travis-Coveralls-Code-Climate/maintainability)

With the output:

Bravo!

Step 10:

Final testing and scaling the api

Wow! This article is about 12 minutes read. I admire your patience to see the very end. However, I can’t call this the end because, there are still some stuffs to do, which, you wont have issues executing i guess.

a. You can host the application on <a href="https://heroku.com/" target="_blank">Heroku</a>

b. You can create more endpoints

c. You can write more test cases

d. And lots more.

Conclusion

I hope you didn’t have too much trouble following the instructions in this article. This article is very basic, meaning that you can apply the knowledge gained here to any similar project you are currently working on.

Get the source code here: github

Thanks for reading ❤

#node-js #express #postgresql

Adonis  Kerluke

Adonis Kerluke

1596509565

RESTful API Design Driven Approach

In this tutorial I will show you the fundamentals of designing a RESTful API specification by applying REST principles and best practices, then you’ll be ready to try my online tutorial: How to design a REST API with API Designer?

If you already know what is meant by API in the context of RESTful web services, you can skip to the next section. If not, read on.

Level-Set on API

The abbreviation API stands for Application Programming Interface this in itself, does not help us understand what it is, however in the context of web services, it can refer to one of two things:

  1. The RESTful API specification is written using a modeling language such as Open API specification or RAML (RESTful API Modeling Language) that defines a contract for how software components can interact with a service.
  2. The implementation of a web service or microservice whose contract is designed by REST principles that describe how other services must interact with it.

In this post, I will use the first understanding of this term. Even though both are correct, the most technically relevant for this post is the first: an API is a contract for how software applications talk to each other.

Level-Set on REST

The acronym REST stands for REpresentational State Transfer. It is an architectural style used to represent the transmission of data from one application component to another. In the context of web services, we are talking about the representation of resources (i.e. data) transferred over HTTP by calling a URI that represents the data and via an HTTP method that represents the action to perform against the given data.

What Is RESTful API design?

RESTful API design is the activity of describing the behavior of a web service in terms of its data structures and the actions you allow other application components to perform on its data by the principles of REST. Those principles are covered later in this blog.

Why Design a RESTful API?

Imagine that you are an Architect (the kind the design building) and you set out to build an office block without a blueprint. You turn up on the first day with a truck full of bricks and some cement. What are the chances that you’ll be successful and build a structure that conforms to code and more importantly, doesn’t fall? It’s about zero. Without a blueprint the chance of failure is high.

The same approach applies to web service development. You need a blueprint, or more appropriately, an API specification. This is necessary to evaluate the API design and solicit feedback before even starting to build the implementation.

In addition to providing a specification for the web service’s development, an API contract serves to document its expected behavior, data types, and security requirements.

You should now be satisfied that API design is necessary for a RESTful web service, and should start to wonder how is the best approach to actually designing an API specification.

API Design Tooling

The tooling chosen by an API designer has substantial influence over the designer’s productivity. Highly productive tools such as the Anypoint API Designer from MuleSoft is perfect for designing APIs with OAS (swagger) or RAML.

#integration #api #rest #rest api #restful #api design #raml #rest api design