MEAN.JS - REST API



In this chapter, we will see our application interacting via a REST API with our database by using HTTP methods. The term REST stands for REpresentational State Transfer, which is an architectural style designed to communicate with web services and API stands for Application Program Interface that allows interacting applications with each other.

First, we will create RESTful API to get all items, create the item and delete an item. For each item, _id will be generated automatically by MongoDB. The below table describes how application should request data from API −

HTTP Method URL Path Description
GET

/api/students

It is used to get all the students from collection Student.
POST

/api/students/send

It is used to create a student record in collection Student.
DELETE

/api/students/student_id

It is used to delete a student record from collection Student.

RESTful API Routes

We will first discuss Post Method in RESTful API Routes.

POST

First let's create a record in the collection Student via our REST API. The code for this particular case can be found in server.js file. For reference, a part of code is pasted here −

app.post('/api/students/send', function (req, res) {
   var student = new Student(); // create a new instance of the student model
   student.name = req.body.name; // set the student name (comes from the request)
   student.save(function(err) {
      if (err)
         res.send(err);
         res.json({ message: 'student created!' });
   });
});

Execution

You can download the source code for this application in this link. Download the zip file; extract it in your system. Open the terminal and run the below command to install npm module dependencies.

$ cd mean-demon-consuming_rest_api
$ npm install

To parse the request, we would need body parser package. Hence, run the below command to include in your application.

npm install --save body-parser

The attached source code already has this dependency, hence no need to run the above command, it is just for your info.

To run the application, navigate to your newly created project directory and run with the command given below −

npm start

You will get a confirmation as shown in the image below −

Execution

There are many tools to test the API calls, here we are using one of the user friendly extensions for Chrome called Postman REST Client.

Open the Postman REST Client, enter the URL as http://localhost:3000/api/students/send, select the POST method. Next, enter request data as shown below −

Post Method

Notice that we are sending the name data as x-www-form-urlencoded. This will send all of our data to the Node server as query strings.

Click on the Send button to create a student record. A success message will appear as shown below −

Student Record

GET

Next, let’s get all the student records from the mongodb. Following route needs to be written. You can find full code in server.js file.

app.get('/api/students', function(req, res) {
   // use mongoose to get all students in the database
   Student.find(function(err, students) {
      // if there is an error retrieving, send the error.
      // nothing after res.send(err) will execute
      if (err)
         res.send(err);
      res.json(students); // return all students in JSON format
   });
});

Next, open the Postman REST Client, enter the URL as

http://localhost:3000/api/students, select the GET method and click on the Send button to get all the students.

GET Method

DELETE

Next, let's see how to delete a record from our mongo collection via REST api call.

Following route needs to be written. You can find full code in server.js file.

app.delete('/api/students/:student_id', function (req, res) {
   Student.remove({
      _id: req.params.student_id
   }, function(err, bear) {
      if (err)
         res.send(err);
      res.json({ message: 'Successfully deleted' });
   });
});

Next, open the Postman REST Client, enter the URL as

http://localhost:3000/api/students/5d1492fa74f1771faa61146d

(here 5d1492fa74f1771faa61146d is the record we will be deleting from the collection Student).

Select the DELETE method and click on the Send button to get all the students.

Delete Method

You can check the MongoDB for the deleted data, by making GET call to http://localhost:3000/api/students/5d1492fa74f1771faa61146d.

Advertisements