DEV Community

Shriansh Agarwal
Shriansh Agarwal

Posted on

API Requests in Javascript

GET Request

To make a GET request in JavaScript, you can use the following code:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
Enter fullscreen mode Exit fullscreen mode

POST Request

To make a POST request in JavaScript, you can use the following code:

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Shriansh Agarwal',
    email: 'shriansh@example.com'
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
Enter fullscreen mode Exit fullscreen mode

PUT Request

To make a PUT request in JavaScript, you can use the following code:

fetch('https://api.example.com/data/123', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Shriansh Agarwal',
    email: 'shriansh@example.com'
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
Enter fullscreen mode Exit fullscreen mode

DELETE Request

To make a DELETE request in JavaScript, you can use the following code:

fetch('https://api.example.com/data/123', {
  method: 'DELETE'
})
  .then(response => console.log('Record deleted'))
  .catch(error => console.error(error))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)