How to call a REST web service API from JavaScript?

Shaik Syed Ali picture Shaik Syed Ali · May 2, 2016 · Viewed 557.2k times · Source

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.

Answer

Brendan McGill picture Brendan McGill · Aug 15, 2018

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('http://example.com/movies.json');
  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('http://example.com/movies.json', {
    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
}