Middle
Tell me about HTTP request methods and their main differences (GET, POST, PUT, DELETE, PATCH, HEAD).
sobes.tech AI
Answer from AI
HTTP methods define the action that the client wants to perform on a resource on the server:
- GET — requests data from the server. A safe and idempotent method, it should not change the server's state.
- POST — sends data to the server to create a new resource or perform an operation. Not idempotent.
- PUT — completely replaces an existing resource or creates it if it does not exist. Idempotent.
- DELETE — deletes the specified resource. Idempotent.
- PATCH — partially updates a resource by sending only the changed fields. Not always idempotent.
- HEAD — requests only the response headers, without the body. Used to check the existence of a resource or metadata.
Example usage in fetch (JavaScript):
// GET request
fetch('/api/items')
.then(res => res.json())
.then(data => console.log(data));
// POST request
fetch('/api/items', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name: 'New Item'})
});