Defining the API routes

One of the most important aspects of our API are routes that we take to create, read, update, and delete our speakers.

Our routes are based on the HTTP verb used to access our API, as shown in the following examples:

  • To create record, use the POST verb
  • To read record, use the GET verb
  • To update record, use the PUT verb
  • To delete records, use the DELETE verb

So, our routes will be as follows:

Routes

Verb and Action

/api/speakers

GET retrieves speaker's records

/api/speakers/

POST inserts speakers' record

/api/speakers/:speaker_id

GET retrieves a single record

/api/speakers/:speaker_id

PUT updates a single record

/api/speakers/:speaker_id

DELETE deletes a single record

Configuring the API routes:

  1. Let's start defining the route and a common message for all requests:
    var Speaker     = require('./server/models/speaker'),
    
    // Defining the Routes for our API
    
    // Start the Router
    var router = express.Router();
    
    // A simple middleware to use for all Routes and Requests
    router.use(function(req, res, next) {
    // Give some message on the console
    console.log('An action was performed by the server.'),
    // Is very important using the next() function, without this the Route stops here.
    next();
    });
    
    // Default message when access the API folder through the browser
    router.get('/', function(req, res) {
    // Give some Hello there message
    res.json({ message: 'Hello SPA, the API is working!' });
    });
  2. Now, let's add the route to insert the speakers when the HTTP verb is POST:
    // When accessing the speakers Routes
    router.route('/speakers')
    
    // create a speaker when the method passed is POST
    .post(function(req, res) {
    
    // create a new instance of the Speaker model
    var speaker = new Speaker();
    
    // set the speakers properties (comes from the request)
      speaker.name = req.body.name;
      speaker.company = req.body.company;
      speaker.title = req.body.title;
      speaker.description = req.body.description;
      speaker.picture = req.body.picture;
      speaker.schedule = req.body.schedule;
    
    // save the data received
      speaker.save(function(err) {
        if (err)
          res.send(err);
    
    // give some success message
      res.json({ message: 'speaker successfully created!' });
      });
    })
  3. For the HTTP GET method, we need this:
    // get all the speakers when a method passed is GET
    .get(function(req, res) {
      Speaker.find(function(err, speakers) {
        if (err)
          res.send(err);
    
        res.json(speakers);
      });
    });

Note that in the res.json() function, we send all the object speakers as an answer. Now, we will see the use of different routes in the following steps:

  1. To retrieve a single record, we need to pass speaker_id, as shown in our previous table, so let's build this function:
    // on accessing speaker Route by id
    router.route('/speakers/:speaker_id')
    
    // get the speaker by id
    .get(function(req, res) {
      Speaker.findById(req.params.speaker_id, function(err, 
        speaker) {
        if (err)
          res.send(err);
          res.json(speaker);
        });
    })
  2. To update a specific record, we use the PUT HTTP verb and then insert the function:
    // update the speaker by id
    .put(function(req, res) {
      Speaker.findById(req.params.speaker_id, function(err, speaker) {
    
        if (err)
          res.send(err);
    
    // set the speakers properties (comes from the request)
      speaker.name = req.body.name;
      speaker.company = req.body.company;
      speaker.title = req.body.title;
      speaker.description = req.body.description;
      speaker.picture = req.body.picture;
      speaker.schedule = req.body.schedule;
    
    // save the data received
      speaker.save(function(err) {
        if (err)
          res.send(err);
          // give some success message
          res.json({ message: 'speaker successfully updated!'});
      });
    
      });
    })
  3. To delete a specific record by its id:
    // delete the speaker by id
    .delete(function(req, res) {
      Speaker.remove({
        _id: req.params.speaker_id
      }, function(err, speaker) {
        if (err)
          res.send(err);
    
    // give some success message
      res.json({ message: 'speaker successfully deleted!' });
      });
    });
  4. Finally, register the Routes on our server.js file:
    // register the route
    app.use('/api', router);

All necessary work to configure the basic CRUD routes has been done, and we are ready to run our server and begin creating and updating our database.

Open a small parenthesis here, for a quick step-by-step process to introduce another tool to create a database using MongoDB in the cloud.

There are many companies that provide this type of service but we will not go into individual merits here; you can choose your preference. We chose Compose (formerly MongoHQ) that has a free sandbox for development, which is sufficient for our examples.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.80.100