RESTful API #opinions

Did some research on RESTful API's again this morning because I wanted to be very clear of why I do what I am doing. This is a note on how I decide what to do and when to do it.

Using a recent RESTful resource I created in a Rails 5 app creates the following routes.

routes.rb

resources :contacts  

rake routes produces

       contacts GET    /contacts(.:format)     contacts#index
                POST   /contacts(.:format)     contacts#create
        contact GET    /contacts/:id(.:format) contacts#show
                PATCH  /contacts/:id(.:format) contacts#update
                PUT    /contacts/:id(.:format) contacts#update
                DELETE /contacts/:id(.:format) contacts#destroy

GET#index in this case returns a list of contacts. Depending on implementation, we could add pagination and all sorts of good front end goodies here. In this article it just returns all of your contacts.

GET#show requires a resource identifier and signifies we are going after a very specific resource, the identifier is unique.

POST#create is submitted to the generic /contacts route and this would be how we create a resource, given we don't have an ID. POSTing the valid data would in fact return a new resource with an identifier

DELETE#destroy is fairly self explanatory and it removes a resource by identifier

PUT vs. PATCH

A PUT#update should be used when completely overwriting a resource as it is described to be idempotent (definition: denoting an element of a set that is unchanged in value when multiplied or otherwise operated on by itself.)

A PATCH#update should be able to identify and change only a specific field or set of fields (merging may come to mind).

In an extremely large object we may want to update fields independently in several requests instead of one single huge request. This scenario would suggest you use PATCH instead of PUT.

Up for interpretation may be the specifics around when to use POST vs. PUT. I would think that POST and PATCH are synonymous and open to very specific routines when a resource is identified.

References

StackOverflow (POST vs. PUT)

REST w3c

Idempotent