So far as I know, four kind of methods are used in RESTful APIs:
GET for getting the resource.
POST for updating the resource.
PUT for creating or substituting the resource.
DELETE for deleting the resource.
Assume we have a resource named apple, and we can 'update' it in several ways. For example, pare it, slice it, or make it apple juice.
Each of these three different updating actions takes different arguments, and of their APIs, the common part will be:
POST /apple HTTP/1.1
Host: www.example.com
<different combination of arguments>
In this situation, three APIs share the same URI and the same request method, the only differences of them are arguments. I think this forces the backend to be ready for accepting the union set of those arguments, and to distinguish which action is actually requested, the backend need to check out the combination of the arguments. It's so much complicated and not graceful.
So my question is:
In this apple cases, how to work out an elegant set of RESTful APIs which make the backend easily handle with it.
First of all, try to avoid conflating HTTP methods to CRUD operations. I believe that's the main source of confusion in REST. HTTP methods don't translate to CRUD operations cleanly like that. I have a detailed answer here:
In short.
Now, on the backend side, try to think of REST resources more like a state machine where you can use the methods to force a transition rather than an object with methods. That way you focus the implementation on the resource itself, not on the interaction with the protocol. For instance, you may change an object's attributes straightforwardly from the method's payload, and then have a method that's called to detect what transition is needed.
For instance, you may think of an apple as having three states, whole, pared, sliced and juiced. You transition between states by using the standardized behavior of the methods.
For instance:
GET /apple
{"state": "whole",
"self": "/apple"}
Then you want to slice it. You may do something like:
PUT /apple
{"state": "sliced"}
Or you may do something like:
PATCH /apple
{"from_state": "whole", "to_state": "sliced"}
Or even something like:
POST /apple
{"transition": "slice"}
The idea is that the implementations can be generic enough that you don't have to worry too much about coupling the resource to the HTTP methods.
As long as your implementation of the resource understands that when apple.state
is changed to something else it should detect what change occurred and perform the adequate transition, you are completely decoupled from the protocol. It doesn't matter what method was used.
I believe this is the most elegant solution, and makes everything easier to handle from the backend side. You can implement your objects without worrying too much about the protocol. As long as the objects can be transitioned between states, they can be used by any protocol that can effect those transitions.