DEV Community

Cover image for Making API calls in JavaScript.
Ebenezer Awuku
Ebenezer Awuku

Posted on • Updated on

Making API calls in JavaScript.

To make an API call in JavaScript, you can use the fetch() function. This function allows you to make requests to a specified URL and return the response in the form of a promise, which you can then process further as needed.

Here's an example of how you might use the fetch() function to make a GET request to an API endpoint:

fetch('https://www.example.com/api/endpoint')
  .then(response => response.json())
  .then(data => {
    // do something with the data
  });

Enter fullscreen mode Exit fullscreen mode

In this example, the fetch() function makes a GET request to the specified URL, and then the resulting promise is processed with the .then() method. The first .then() method call takes the response from the request and converts it to a JSON object, which is then passed to the second .then() method as the data argument.

You can also use the fetch() function to make other types of requests, such as POST, PUT, and DELETE, by passing an options object as the second argument to the function. For example:

fetch('https://www.example.com/api/endpoint', {
  method: 'POST',
  body: JSON.stringify({
    key: 'value'
  }),
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => {
    // do something with the data
  });

Enter fullscreen mode Exit fullscreen mode

In this example, the fetch() function makes a POST request to the specified URL, and the options object passed as the second argument specifies that the request body should be a JSON object with a key and a value property. The headers property is used to set the Content-Type of the request to application/json.

I hope this helps!

Oldest comments (0)