How to call a REST web service API from JavaScript?

I have an HTML page with a button on it. When I click on that button, I need to call a REST Web Service API. I tried searching online everywhere. No clue whatsoever. Can someone give me a lead/Headstart on this? Very much appreciated.


I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.

The API includes a lot more, but start with the fetch() method. It takes two arguments:

  1. A URL or an object representing the request.
  2. Optional init object containing the method, headers, body etc.

Simple GET:

const userAction = async () => {
  const response = await fetch('');
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson

Recreating the previous top answer, a POST:

const userAction = async () => {
  const response = await fetch('', {
    method: 'POST',
    body: myBody, // string or object
    headers: {
      'Content-Type': 'application/json'
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson

Your Javascript:

function UserAction() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
    };"POST", "Your Rest URL Here", true);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send("Your JSON Data Here");

Your Button action::

<button type="submit" onclick="UserAction()">Search</button>

For more info go through the following link (Updated 2017/01/11)

Here is another Javascript REST API Call with authentication using json:

<script type="text/javascript" language="javascript">

function send()
    var urlvariable;

    urlvariable = "text";

    var ItemJSON;

    ItemJSON = '[  {    "Id": 1,    "ProductID": "1",    "Quantity": 1,  },  {    "Id": 1,    "ProductID": "2",    "Quantity": 2,  }]';

    URL = "" + urlvariable;  //Your URL

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = callbackFunction(xmlhttp);"POST", URL, false);
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('apiusername:apiuserpassword')); //in prod, you should encrypt user name and password and provide encrypted keys here instead 
    xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
    document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";

function callbackFunction(xmlhttp) 

<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>


           "key":"your key",
     "Accept":"application/json",//depends on your api
      "Content-type":"application/x-www-form-urlencoded"//depends on your api
        },   url:"url you need",
          var r=JSON.parse(response);

I think add if (this.readyState == 4 && this.status == 200) to wait is better:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
        var response = xhttp.responseText;
};"GET", "your url", true);


Before we try to put anything on the front end of the website, let's open a connection the API. We'll do so using XMLHttpRequest objects, which is a way to open files and make an HTTP request.

We'll create a request variable and assign a new XMLHttpRequest object to it. Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint. The request completes and we can access the data inside the onload function. When we're done, we'll send the request. // Create a request variable and assign a new XMLHttpRequest object to it. var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint'GET', '', true)

request.onload = function () {
  // Begin accessing JSON data here

// Send request

Usual way is to go with PHP and ajax. But for your requirement, below will work fine.


<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<div id="display"></div>

<script type="text/javascript">

document.getElementById('sub').onclick = function(){

var url = document.getElementById('url').value;
var controller = null; 
var method = null; 
var parm = []; 

//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4]; 
parm[0] = x[5]; 
parm[1] = x[6];

function Add(a,b){
return Number(a)+ Number(b);
function Sub(a,b){
return Number(a)/Number(b);
function Multi(a,b){
return Number(a)*Number(b);

//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);

function ProcessRequest(){

}else if(method=="Sub"){
}else if(method=="Multi"){
}else {
    ResponseRequest("404","Not Found");




Need Your Help

How do I manipulate $PATH elements in shell scripts?

unix shell idioms path-variables

Is there a idiomatic way of removing elements from PATH-like shell variables?

Using multiple criteria in subset function and logical operators

r statistics subset logical-operators operator-precedence

If I want to select a subset of data in R, I can use the subset function. I wanted to base an analysis on data that that was matching one of a few criteria, e.g. that a certain variable was either ...