RESTful API

NodeJS is the most suitable for constructing RESTful APIs.

Representational state transfer (REST) is a Architectural style used 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 res.json() or res.send() with the data in JSON or text Format.

The Express response object provides methods such as res.send() and res.json() to send data back to the client. The return keyword is optional and is commonly used to stop further execution after sending a response.

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

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

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

Run API

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

node src/app.js

AJAX or Fetch 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 or Fetch API.

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.

Enable CORS Policies in Node

To allow cross origin, we have to set headers for Access-Control-Allow-Origin. The possible value are wildcard ( * ), origin or null (not recommended).

Access-Control-Allow-Origin with * value is wildcard. This will allow request from any origin.

Access-Control-Allow-Origin with origin value specific for domain only. Exp techaltum.com . This will allow request from only techaltum.com domain.

For production code, prefer using CORS Middleware

Node JS Code

     /*app.js*/

import express from '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`);
});

Frontend Code using AJAX

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


<script>
const 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>

Frontend Code using Fetch API

Use JavaScript fetch api to get data from the server asynchronously.


    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 or Fetch api

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*/
import express from 'express';
let app=express();

app.use(express.json());
app.use(express.urlencoded({extended:true}));


app.post('/search',(req,res)=>{
    const data=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",
            headers: {'Content-Type': 'application/json'},
            body:JSON.stringify({name:this.value})}
            })
            .then(res=>res.json())
            .then(i=>console.log(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.setRequestHeader(
    "Content-Type",
    "application/json"
    );

    xhr.send(JSON.stringify({
        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>


CORS

Cross-Origin Resource Sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated.

For API, prefer using CORS headers to handle cross-origin requests.


import express from 'express';
import cors from 'cors';

const app = express();

app.use(cors({
    origin: 'http://localhost:8080'
}));

app.use(express.json());

app.post('/search', (req, res) => {
    const name = req.body.name;

    res.json({
        message: `Hello ${name}`,
        received: name
    });
});

app.listen(8080, () => {
    console.log('Server running on port 8080');
});