Most Common HTTP Request Methods — POST, GET, PUT, PATCH, and DELETE. A walkthrough with JavaScript’s Fetch API.
POST, GET, PUT, PATCH, and DELETE are the most-commonly-used HTTP verbs. These correspond to the CRUD (create, read, update, and delete) operations respectively. There are a number of other verbs too, but these are utilized less frequently.
- POST — CREATE a new record
- GET — READ
- PUT —UPDATE If the record exists else CREATE a new record
- PATCH — UPDATE (modify)
- DELETE — DELETE
I will be using this fake API for a demonstration. with credits to https://jsonplaceholder.typicode.com/albums
The POST method
POST method used to submit an entity to the server and creates a new resource. In particular, it’s used to create subordinate resources. When a new resource is posted successfully, the API service will automatically associate the new resource by assigning it an ID (new resource URI). In sort, the POST method is used to insert new items in the backend server and it performs the create operation of the CRUD operation. It returns an HTTP status code 201 on successful creation.
The GET Method
The GET method is used to retrieve data from the server. The GET is a read-only method, so there has no risk of corrupting the data. In the success case, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).
The PUT Method
The PUT method is used to update an existing resource. Firstly, The resource is identified by the URL and if it exists, then it is updated, otherwise, a new resource is created. The PUT is idempotent: means, calling the PUT method one or several time successively has the same effect (no side effect), whereas calling a POST(non-idempotent) request repeatedly have side effects of creating the same resource multiple times. PUT return HTTP status 200 on successful update and HTTP status 201 on successful creation.
The PATCH method
PATCH is very similar to the PUT method. It is used to apply partial modifications to an existing resource. The difference is that, in the PUT method the request-body
contains the completely new version, whereas in the PATCH method the request-body
contains the specific changes to the resource. A PATCH is not necessarily idempotent, although it can be. Contrast this with PUT; which is always idempotent.
The DELETE Method
The DELETE method deletes the specified resource by its URI. It returns an HTTP status code 202 (Accepted) if the action will probably succeed but has not been implemented yet. On successful deletion, it returns an HTTP status code 200 (OK). If the action has been implemented and no further information is to be supplied then it returns status code 204 (No Content).
References:
https://www.restapitutorial.com/lessons/httpmethods.html