Senior
Tell me about HTTP methods: which ones do you know, how does PUT differ from POST, GET from POST, and what is PATCH used for?
sobes.tech AI
Answer from AI
HTTP methods define the type of operation the client wants to perform on a resource on the server:
- GET — request to retrieve data. Safe and idempotent method, should not change the server's state.
- POST — send data to the server to create a new resource or perform an operation. Not idempotent.
- PUT — replace an existing resource or create it if it does not exist. Idempotent (repeated requests give the same result).
- PATCH — partial update of a resource, modifies only specified fields.
- DELETE — delete a resource.
Differences between PUT and POST:
- PUT is usually used for updating or creating a resource at a known URI, and is idempotent.
- POST is used for creating a resource, the URI may not be fixed, and is not idempotent.
Differences between GET and POST:
- GET requests data, parameters are passed in the URL, safe and idempotent.
- POST sends data in the request body, used for creating or modifying data, not idempotent.
Why PATCH is needed:
- PATCH allows updating only part of a resource, which is more efficient than sending the entire object via PUT, especially with large data.
Example of using PATCH:
PATCH /users/123 HTTP/1.1
Content-Type: application/json
{"email": "newemail@example.com"}