How To Make Api Request In Javascript

March 7, 2023, 2:03 p.m.

api web development javascript

API requests in JavaScript are used to retrieve or send data to a server using the XMLHttpRequest object. The XMLHttpRequest object provides an easy way to send HTTP requests and receive responses from a server asynchronously. Here are the steps to make an API request in JavaScript:

XmlHttpRequest Object

Create an instance of the XMLHttpRequest object: To make an API request, first, we need to create an instance of the XMLHttpRequest object. We can create it using the following code:

const xhr = new XMLHttpRequest();

Add method and url

Specify the request method and URL: After creating the XMLHttpRequest object, we need to specify the request method and URL to send the request. We can do it using the following code:

xhr.open('GET', 'https://api.example.com/data');

Here, we are specifying a GET request method and the URL of the API endpoint.

Request Header

Set request headers (optional): If the API requires any specific headers, we can set them using the setRequestHeader() method of the XMLHttpRequest object. For example, if the API requires an authentication token, we can set it as follows:

xhr.setRequestHeader('Authorization', 'Bearer <token>');

Send Request

Send the request: After setting the request method, URL, and headers (if required), we can send the request using the send() method of the XMLHttpRequest object. We can do it using the following code:

xhr.send();

Handle Response

Handle the response: Once the API request is sent, we need to handle the response from the server. We can do it using the following code:

xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.response);
  } else {
    console.log('Error: ' + xhr.status);
  }
};

Here, we are using the onload event handler to handle the response. If the response status is 200 (OK), we are logging the response to the console. Otherwise, we are logging an error message along with the status code.

Handle Errors

Handle errors (optional): In addition to handling the response, we may also need to handle any errors that occur during the API request. We can do it using the onerror event handler of the XMLHttpRequest object. For example, we can log an error message if the request fails as follows:

xhr.onerror = function() {
  console.log('Error: ' + xhr.status);
};

Here, we are using the onerror event handler to log an error message if the request fails.

Query Parameters

Add query parameters (optional): If the API requires any query parameters, we can add them to the request URL. For example, if the API requires a search query, we can add it as follows:

const searchQuery = 'example';
xhr.open('GET', 'https://api.example.com/data?q=' + encodeURIComponent(searchQuery));

Here, we are adding the search query to the request URL using the encodeURIComponent() method to encode any special characters.

Request Body

Add a request body (optional): If the API requires any data to be sent in the request body, we can add it using the send() method of the XMLHttpRequest object. For example, if the API requires a POST request with JSON data, we can do it as follows:

const data = { name: 'John Doe', email: '[email protected]' };
xhr.open('POST', 'https://api.example.com/users');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));

Here, we are setting the request method to POST, adding the Content-Type header to indicate that the request body is in JSON format, and sending the JSON data using the send() method.

author image

bracketcoders

A learing portal for your coding interest.

View Profile