Monday, 8 April 2019

REST managing state

REST managing state 

Managing state in REST can be quite challenging. The change in state may trigger different validation and business rules used to process that payload. Rather than using complex logic we could use the resource paths to model the representation of each state. 

Example 

Modifying the pre-approval and post-approval of a workflow item. Below is an invoice that requires approval for payment. 


Invoice creation state 

POST /invoice 
{
"invoiceId": 1000,
"invoiceDate": "02/04/2001",
"vendorName": "XYZ Industries Ltd",
"approving Manager": null,
"accountNumber": null
}

Invoice approval state

PUT /invoice/1000/approval 
{
"invoiceDate": "02/04/2001",
"vendorName": "XYZ Industries Ltd",
"approving Manager": "Tom",
"accountNumber": null
}
   
Invoice payment state

PUT /invoice/1000/payment 
{
"invoiceDate": "02/04/2001",
"vendorName": "XYZ Industries Ltd",
"approving Manager": "Tom",
"accountNumber": 6597465923056
}

REST design

PATCH method

Below is an example of how to use PATCH and over come ambiguity of identifying which fields need to be modified vs those that don't.


PATCH /path/myAPI

{"key":"FieldName","Value":"someValue"}


There is a very good article from 
William Durand please-do-not-patch-like-an-idiot. He goes further in its use to specify various operations that can be achieved with the PATCH method. Which addresses the common design problem in a PATCH call, differentiating a request value to be set to null as opposed to using null to retain its current state.