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

Neon image

⚡ Set up a Neon project in seconds and connect from a Next.js application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Top comments (0)

👋 Kindness is contagious

If this post resonated with you, feel free to hit ❤️ or leave a quick comment to share your thoughts!

Okay