Sobes.tech
Junior

What is the difference between PUT and POST requests?

sobes.tech AI

Answer from AI

PUT is used to create or update a resource at a specified URI. It is idempotent, meaning that multiple identical PUT requests should result in the same resource state.

POST is used to send data to the server and can create a new resource, update an existing one, or perform other operations. It is not idempotent, and multiple identical POST requests may result in multiple resources being created or multiple operations being performed.

Main differences:

Characteristic PUT POST
Usage Create/update at URI Send data, create/update
Idempotency Yes No
URI Specifies the target resource Specifies the resource for data processing
Result Replace/create resource at URI Change server state

Example of using PUT (create or update user with ID 1):

// Assume we have a user data object
const userData = {
  name: "Ivan",
  age: 30
};

fetch('/api/users/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(userData)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Example of using POST (create a new user):

// Assume we have a new user data object
const newUser = {
  name: "Petr",
  age: 25
};

fetch('/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(newUser)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));