Setup Project

  • mkdir <projectdir>/helloworld
  • cd helloworld
  • npm init
    • name:
    • version:
    • description: Hello World API
    • entry point: server.js
    • test command:
    • git repository:
    • keywords:
    • author: John Dunning
    • license:
  • npm install –save express body-parser mongoose bluebird
  • npm install -g nodemon
  • atom .

Create server.js

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose')
mongoose.Promise = require('bluebird');

var Person = require('./app/model/person');

var app = express();

// Configure app for bodyParser()
// grab data from body of POST

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// Set up server port to listen on

var port = process.env.PORT || 3000;

// Connect to Database

mongoose.connect('mongodb://localhost:27017/people', {
  useMongoClient: true,
  /* other options */
});

// API Routes

var router = express.Router();

// Routes will all be prefixed with /api

app.use('/api', router);

// MiddleWare ; Validate request

router.use(function(req, res, next) {
  console.log('MiddleWare - Validate request');
  next();
});

// Test Route

router.get('/', function(req, res) {

  res.json({message: 'Welcome to the Hello World API'})

});

// Person Route

router.route('/person')

  .post(function(req, res) {
    var person = new Person();
    person.firstname = req.body.firstname;
    person.lastname = req.body.lastname;
    person.age = req.body.age;

    person.save(function(err) {
      if(err) {
        res.send(err);
      }

      res.json({message: person.firstname+" "+person.lastname+" was successfully added"})
    });
  })

  .get(function(req, res) {
    Person.find(function(err,people) {
      if(err) {
        res.send(err);
      }

      res.json(people);
    });
  });

  router.route('/person/:person_id')
    .get(function(req,res) {
      Person.findById(req.params.person_id, function(err, person) {
        if(err) {
          res.send(err);
        }

        res.json(person);
      });
    });

    router.route('/person/lastname/:lastname')
      .get(function(req,res) {
        Person.find({ lastname: req.params.lastname}, function(err, person) {
          if(err) {
            res.send(err);
          }

          res.json(person);
        });
      });

      router.route('/person/age/:age')
        .get(function(req,res) {
          Person.find({ age: req.params.age}, function(err, person) {
            if(err) {
              res.send(err);
            }

            res.json(person);
          });
        });
// Start the server

app.listen(port);

// Print a friendly message

console.log('Server listening on port '+port);

Create Model

  • open Atom
  • create folders
    •  app
    • app/model
    • app/model/person.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var PersonSchema = new Schema({
  firstname: String,
  lastname: String,
  age: Number
});

module.exports = mongoose.model('Person',PersonSchema);

Start MongoDB

  • mongod

Start the Server

  • nodemon server.js

Check the Response

  • open Postman
    • GET localhost:3000/api
{
    "message": "Welcome to the Hello World API"
}

Postman

POST localhost:3000/api/person

  • Headers
    • Content-Type
    • application/json
  • Body
    • raw
{
    "firstname": "Jon",
    "lastname": "Doe",
    "age": 21
}

Send

{
    "firstname": "Jane",
"lastname": "Doe",
"age": 19
}

Send

{
"firstname": "Mick",
"lastname": "Doe",
"age": 14
}

Send

{
"firstname": "Andy",
"lastname": "Doe",
"age": 8
}

Send

GET localhost:3000/api/person

[
    {
        "_id": "5999c4c26604ae6a1da7e1f6",
        "age": 21,
        "lastname": "Doe",
        "firstname": "Jon",
        "__v": 0
    },
    {
        "_id": "5999c4fcd77e466a3db7b05c",
        "age": 19,
        "lastname": "Doe",
        "firstname": "Jane",
        "__v": 0
    },
    {
        "_id": "5999c5540a3fd46a6854adca",
        "age": 14,
        "lastname": "Doe",
        "firstname": "Mick",
        "__v": 0
    },
    {
        "_id": "5999c57b70f4b66a7b58073d",
        "age": 8,
        "lastname": "Doe",
        "firstname": "Andy",
        "__v": 0
    }
]

GET localhost:3000/api/person/5999c4fcd77e466a3db7b05c

{
    "_id": "5999c4fcd77e466a3db7b05c",
    "age": 19,
    "lastname": "Doe",
    "firstname": "Jane",
    "__v": 0
}

GET localhost:3000/api/person/lastname/Doe

[
    {
        "_id": "5999c4c26604ae6a1da7e1f6",
        "age": 21,
        "lastname": "Doe",
        "firstname": "Jon",
        "__v": 0
    },
    {
        "_id": "5999c4fcd77e466a3db7b05c",
        "age": 19,
        "lastname": "Doe",
        "firstname": "Jane",
        "__v": 0
    },
    {
        "_id": "5999c5540a3fd46a6854adca",
        "age": 14,
        "lastname": "Doe",
        "firstname": "Mick",
        "__v": 0
    },
    {
        "_id": "5999c57b70f4b66a7b58073d",
        "age": 8,
        "lastname": "Doe",
        "firstname": "Andy",
        "__v": 0
    }
]

GET localhost:3000/api/person/age/14

[
    {
        "_id": "5999c5540a3fd46a6854adca",
        "age": 14,
        "lastname": "Doe",
        "firstname": "Mick",
        "__v": 0
    }
]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s