RESTful API

NodeJS is best to build RESTful APIs.

Representational state transfer (REST) is a Architectural style to build a Web Service or RESTful API. A REST API can response json, html or xml based on http request.

HTTP methods like, GET, POST, PUT, PATCH, DELETE etc can be used with Rest API.

Rest API use stateless protocol for faster transfer, reusability, and reliability in long operations.

REST API can be used in same application or other application on web.


Rest API in NodeJS

Lets create a REST API to transfer Array Data based on http GET method.

    /* app.js*/
const express=require('express');
var app=express();

var data=["sun","mon","tues","wed","thurs","fri","sat"];
    
app.get('/api',()=>{
    return res.send(data);
});

app.listen(3000,()=>{
console.log(`App running`);
});

Run API

["sun","mon","tues","wed","thurs","fri","sat"]

node src/app.js

AJAX Based API

The above api will respond within same app. If we call the api using another ip or domain, we we get an error or CORS policy, i.e

Access to XMLHttpRequest at 'http://127.0.0.1:3000/api' from origin 'http://127.0.0.1:51619' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

To allow cross origin, we have to set headers for Access-Control-Allow-Origin. See example below.

     /*app.js*/

const express=require('express');
var app=express();

var data=["sun","mon","tues","wed","thurs","fri","sat"];
    
app.get('/api',()=>{
    res.header('Access-Control-Allow-Origin',"*");
    return res.send(data);
});

app.listen(3000,()=>{
console.log(`App running`);
});
     /*index.html*/
<h1>AJAX based API</h1>
<p></p>


<script>
var xhr=new XMLHttpRequest();
    
xhr.open("get","http://127.0.0.0:300/api");
xhr.send();

xhr.onreadystatechange=function(){
    
    if( this.readyState==0 || this.readyState==1 || this.readyState==2 ||   this.readyState==3){
        document.querySelector("p").innerHTML="loading data";
    }
    else if(this.readyState==4 && this.status==200){
        document.querySelector("p").innerHTML=this.response;
    }
    else{
        document.querySelector("p").innerHTML="Error Found";
    }
}
</script>

Run API

["sun","mon","tues","wed","thurs","fri","sat"]

node src/app.js

Now open index.htmlin web browser to check api response.