i

Invoking a REST Service

REST stands for Representational State Transfer. It is a web standard architecture and uses HTTP protocol.

It is based on resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. A REST Server simply provides access to resources and clients access and modify the resources using the HTTP protocol. Here each resource is identified by URIs

Resources can be of multiple types like JSON,XML.

HTTP methods

The following four HTTP methods are commonly used in REST-based architecture.

  • GET − This is used to provide read-only access to a resource.

  • POST − This is used to update an existing resource or create a new resource.

  • PUT − This is used to create a new resource.

  • DELETE − This is used to remove a resource.

Let's create a file books.json in the same directory in which resttapi-demo.js is kept.

In a real-world project, you will either be creating REST APIs that will be communicating to the database or you will be accessing existing APIs.

Most big organisations like Google, Facebook, Twitter have their APIs created which you can use to embed their functionality in your applications.

But for this example, we are hardcoding a data file.

Lets see now how REST APIs are being accessed  our client application Restapi-demo.js

Restapi-demo.js

Output

Adding code snippet below to restapi-demo.js

Here, we are hardcoding the book variable value, in a real-world web application, we could have a form taking different attribute values for the book from end-user.

Also, In order to send post request, either you need any form created (having Submit button which eventually generates a POST request) or some postman client.

We are using POSTMAN client here so that we can test our API results. (We have already seen POST request using Form).

Output

First image displaying output in the body section of Postman client

Another one showing console.