REST API Design – Is It Okay to Use POST for Updates?

apiapi-designrestweb-api

For some time I used PUT or PATCH in order to update a REST API resource. After using a lot of PUT/PATCH calls I noticed that "update" could be also done with POST.

Here is an example which is oversimplified that will hopefully explain the situation. There is an endpoint /api/cars/dealers/1 with a resource

{
  "id": 1,
  "dealer_name": "Audi Atlanta",
  "year_opened": 2010,
  "contact_persons": [
    {
      "contact_person_type": "main_contact",
      "contact_person_name": "Mike Smith"
    },
    {
      "contact_person_type": "billing_contact",
      "contact_person_name": "Luke Johnson"
    }
  ]
}

Would it be against REST API guidelines if I update this resource with POST such as

{
  "contact_to_change": "main_contact",
  "contact_name": "John Smith"
}

instead of PATCH with

{
  "id": 1,
  "contact_persons": [
    {
      "contact_person_type": "main_contact",
      "contact_person_name": "Mike Smith"
    }
  ]
}

or instead of full resource update with PUT

Please notice how the structure of payload is completely different then the structure of the resource itself. There are cases when this is much more easier then to go with a raw resource update following the same body structure.

Could this way bring some issue that I don't see at the moment?

Best Answer

You can use POST to update a resource but not using the same URL as the resource you're updating. So, if the URL to use with PUT/PATCH is /api/cars/dealers/1, you'd have /api/cars/dealerupdates to send your POST requests with body as in your PATCH request.

This way it's clear that you're not creating new entity under /api/cars/dealers/ or /api/cars/dealers/1. What created is new update entity which will be applied at some point to the entity inside the request. Another way to see it is: sending GET request to /api/cars/dealerupdates can give a list of updates that have been processed.

Related Topic