REST API: How we implement resource handlers for PATCH req:
PATCH — The HTTP PATCH request method applies partial modifications to a resource. PATCH is somewhat analogous to the “update” concept found in CRUD. A PATCH request is considered a set of instructions on how to modify a resource.
REST API Resource Handlers — are responsible for understanding the client Request and sending back the correct response. It is the callback function/method associated with a Rest Resource. (Do check my earlier post on writing RESTful API Resource Handlers)
We will start with looking the following “ Invitation ” Entity ~
and following is the URI to perform the resource update operation
PATCH /invitations/{id} : Update the Invitation Entity
Actions
There are 3 actions associated with the Invitation entity, End user can either Accept, Reject or Request for a change in the current invitation. Frontend application will make the appropriate HTTP API request to the backend to update the status of the “ Invitation ” entity.
Need for Consistency
- Simple HTTP API contract (request body) across every user action.
- Backend must easily identify the type of action performed and able to validate values sent from the frontend.
- Able to add new action against the “ Invitation ” entity with less efforts.
- Backend must be able to raise exceptions or success response through common channel.
Request Body
Below json shows the request body which we follow across every Entity and its corresponding PATCH HTTP API 💂.
{
"action": "accept|reject|request_change",
"action_arguments": {
"id": 123,
"comments": "Requesting for Change",
"user_email": "change@local.com"
}
}
The action key (string) specifies the name of the action performed by the frontend, action_arguments (object) holds all the values relative to that actions.
Backend Resource Handler
Below is a Pseudo code, on how we implement the resource handler for the “ PATCH ” HTTP request, which accepts only the above sent body 😆
Benefits
- Above approach shows a simple, clean and re-usable approach of writing resource handlers for PATCH HTTP requests.
- Request validation can be done in the respective actionHandler for that action.
- Adding a new action is easy as most of the boiler plate is ready, only thing remains adding a new key=>value pair in the action resolver array and defining the business logic of the function.
- API Resource Handlers are clean and follows its basic responsibility which is to understand the request, delegate to appropriate handler and sending back the response.
Final Notes
We find above to be a better implementation approach in defining the resource handlers for the PATCH HTTP requests.
I am also looking for other ways which can improve the above business need. If there are any please let me know in the comments section below.