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. To send data back to web browser, use return keyword followed by the data in JSON Format.

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

const data=["sun","mon","tues","wed","thurs","fri","sat"];
    
app.get('/api',(req,res)=>{
    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

Learn more about JavaScript AJAX.

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.

Node JS Code

     /*app.js*/

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

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

     // enable CORS policies
    res.header('Access-Control-Allow-Origin',"*");
    return res.send(data);
});

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

Client Side Code

     /*index.html*/
<h1>AJAX based API</h1>
<p></p>


<script>
let xhr=new XMLHttpRequest();
    
xhr.open("get","/api");
xhr.send();

xhr.addEventListener('load',function(){
    
    if(this.readyState==4 && this.status==200){
        document.querySelector("p").innerHTML=this.response;
    }
    else if(this.readyState==4 && this.status==404){
        document.querySelector("p").innerHTML="Page Not Found";
    }
    else{
        document.querySelector("p").innerHTML="Unknown Error";
    }
});
</script>

Fetch API


    fetch('/api').then(i=>i.json()).then(i=>console.log(i));

Run API

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

node src/app.js

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


Send and receive data through AJAX

AJAX can also send data to api through send method. In this example, we will build a Rest API to use two way data binding .

Server Side code

        /*app.js*/
const express=require("express");
let app=express();
const bodyParser=require('body-parser');

app.use(bodyParser.text());

app.post('/search',(req,res)=>{
    let let=req.body;        // receive data through ajax
    res.header('Access-Control-Allow-Origin',"*");
    
    return res.send(data);
});
app.listen(3000);

Client side Using Fetch API

    /*index.html*/

<h1>Fetch API</h1>
<input type="search"> <span></span>


<script>
    let data=document.querySelector("input");
    
    data.addEventListener("input",function(){
        fetch("/search",{method:"POST",body:JSON.stringify({"name":this.value})}}).then(i=>i.json()).fetch(i=>{
            document.querySelector("span").innerHTML=i; 
        });
    });
</script>

Client side using AJAX

        /*index.html*/

    <h1>Ajax based API</h1>
    <input type="search">
    <span></span>
    
<script>
    let input=document.querySelector("input");

    input.addEventListener("input",function(){
    
    let xhr=new XMLHttpRequest();
    
    xhr.open("post","/search");
    xhr.send("name:"+ this.value);
    xhr.addEventListener('readystatechange',function(){
    
    if( this.readyState<=3){
        document.querySelector("span").innerHTML="loading data";
    }
    else if(this.readyState==4 && this.status==200){
        let data=this.response;
        data=JSON.parse(data);
        document.querySelector("span").innerHTML=data;
    }
    else{
        document.querySelector("span").innerHTML="Error Found";
    }
    });
}); 
</script>