Introduction to RESTful API

Introduction to RESTful API

What are REST and RESTful APIs?

APIs (application programming interfaces) serve as a communication channel between two applications, allowing them to communicate and exchange pertinent data. To carry out the operation, a set of protocols are used. A set of guidelines for using when developing web services are defined by the architectural style known as Representational State Transfer (REST). The REST API is a straightforward and versatile method of accessing online services without any processing. Only HTTP requests are used for any communication conducted via REST API.

It is simpler for developers to create and manage web services when using a RESTful API, which is a standardised implementation of the REST architecture. An API must meet the following requirements to be deemed RESTful:

  • An HTTP-based client-server architecture consisting of clients, servers, and resources.

  • Stateless client-server communication means that each request is distinct from the others and that no client data is stored between get requests.

  • Cacheable information that simplifies client-server communications.

HTTP Methods in RESTful API Services

GET:

The GET method is used to retrieve a record or set of records from the server.

app.get('/students', function (req, res) {
    res.json(students);   
});

The students (an array of objects) data is retrieved from the server using the get() method defined in this section of the code. The /students endpoint is listened to by the route that is defined. A callback function that accepts the arguments req (request) and res (response) is the second parameter. The client receives the data using the res.json() function.

POST:

The POST method delivers information to the server to create a new record.

app.post("/students", function (req, res) {
  var student = req.body;  
  students.push(student);
  res.json({ message: "Record Added" });
});

The following line of code defines the post() method, which is used to add new records in students array to the server. It designates a route that attends to the endpoint /students. A callback function with the parameters req( request) and res ( response) is the second one. The request's data is taken out using the req.body parameter, and using the array push() method, it is added to the already-existing list. The acknowledgement message is then returned to the client as JSON data using res.json().

PUT:

The PUT method sends data to update an existing record on the server.

app.put("/students/:name", function (req, res) {
  var updatedName = req.params.name;
  var student=req.body;
  // updating name for all students
  for (var i = 0; i < students.length; i++) {
   if( students[i].name = updatedName)
      students[i]=student;
  }

  res.json({ message: "Record Updated" });
});

Here, the code defines a put() method that is used to update an existing record i.e. ‘student with specific name on the server. It defines a route that listens to the ‘/students/:name’ endpoint. The ‘:name’ here is a URL parameter that is extracted using ‘req.params.name‘. The data passed inside the request body is extracted using ‘req.body’. The student’s data is traversed to find the student with the matching name which on found gets the particular record replaced with new data. Finally, it sends the acknowledgement message back to the client in the form of JSON data using res.json().

PATCH:

PATCH is used to send data to update an "existing record" on the server, just like the PUT method does. But the key distinction between PUT and PATCH is that the latter only makes partial changes to the record rather than completely replacing it.

app.patch("/students/:id", function (req, res) {
  var id = req.params.id;
  var student = req.body;
  var updatedStudent = students.find(function (s) {
    return s.id == id;
  });

  if (updatedStudent) {
    Object.assign(updatedStudent, student);
    res.json({ message: "Record Updated using patch" });
  } else {
    res.status(404).json({ error: "Student not found" });
  }
});

The code defines a patch() method that is used to partially update an existing record i.e. ‘student with specific id’ on the server. It defines a route that listens to the ‘/students/:id’ endpoint. The ‘:id’ here is a URL parameter that is extracted using req.params.id. The data passed inside the request body is extracted using ‘req.body’.We use the Array.prototype.find() method to find the specific student object with the matching ID. If a matching student is found, we use Object.assign() to merge the properties from the student object into the updatedStudent object, effectively updating only the specific properties. Finally, it sends the acknowledgement message back to the client in the form of JSON data using res.json().

DELETE:

The DELETE method is used to delete one or more records from the server.

app.delete("/students/:id", function (req, res) {
  var id = req.params.id;
  for (var i = 0; i < students.length; i++) {
    if (students[i].id == id) {
      students.splice(i, 1);
      break;
    }
  }  
  res.json({ message: "Student Record Deleted" });
});

The code in this section defines the delete() method, which is used to remove an existing record from the server (in this case, "student with specific id"). It specifies a route that monitors the endpoint /students/:id. The :id in this case is an extracted URL parameter from req.params.id. The Array splice() method in Javascript is used to search through the student data ( an array of students) for the student with the matching id, who is then deleted. Finally, it uses res.json() to deliver the acknowledgement message back to the client as JSON data.

Conclusion:

The fundamentals of RESTful API were discussed in this post. We went over the most significant and often used HTTP methods, including GET, POST, PUT, PATCH, and DELETE. One of the key characteristics of this interface is its simplicity, which is made possible by the ease with which REST APIs can be utilised to build services and apps that can be used by a variety of clients and devices. There is much more to investigate and learn—this is only the beginning.

Happy Coding!