Search code examples
resthttp-posthttp-deletehttp-methodhttp-put

Rest Api: When to use Post, PUT, PATCH and Delete


I am working on a restful api and I need to update a resource (i.e. a customer detail record with 10 fields).

On Add request, I send a Post request with complete record. On update request, I send a PUT request with complete record of 10 fields. On Verify request, I send a PUT request with just two fields i.e. recordId and versionNo. On Delete request, I send a DELETE request with two fields in HttpOptions.

I have few questions that:

  • Although, it a restful api but specific application which would be used by an angular application, So should I return data in response of POST/PUT requests.

  • Should I use PATCH in case of Verify (or anyother action where just recordId and versionNo send to server to change some fields) or it is OK to use PUT.

  • To make uniformity, should I send data in body of delete request as I need recordId and versionNo to delete a record.


Solution

  • Should I use PATCH in case of Verify (or anyother action where just recordId and versionNo send to server to change some fields) or it is OK to use PUT.

    In RESTful API designs, PUT requests are generally used to add or replace an entire resource, whereas a PATCH should be just used to update an existing resource. A PUT request is called "idempotent" - no matter how many times you send a PUT response, you should get the same result. A PATCH is not idempotent.

    example:

    PATCH /Cars/vauxhall-astra/engine --> This request would be used to only update the engine of my already existing vauxhall astra

    PUT /Cars/renault-clio --> This request would create a new Renault Clio or, if it already exists, replace the entire Clio using the data specified in my request. A Clio would then be guaranteed to exist after my request is successful, regardless of whether it existed or not before.

    Although, it a restful api but specific application which would be used by an angular application, So should I return data in response of POST/PUT requests.

    Totally up to you, returning data from a POST/PUT is fine - especially if it saves you having to make extra GET api requests. Just always make sure you are only ever returning the data you need from a response.

    To make uniformity, should I send data in body of delete request as I need recordId and versionNo to delete a record.

    Again it's totally up to you. Whether you use query parameters (e.g. DELETE cars?id=123) or a request body is just your preference, there's nothing in REST that has rules for this.