Reputation: 1773
I know that REST endpoints should be nouns instead of verbs, but are slight deviations allowed sometimes?
Imagine an endpoint that should publish a product (make it visible on webpage, maybe add something to a queue).
I can come up with 2 ways to solve this.
1) PUT api/products/1/publish - I like it because it is explicit, avoids complexity on the backend and it documents it self.
2) PATCH/PUT/PATCH api/products/1
{
"color": "green",
//some properties removed for brevity
"ispublished" : true
}
The second approach requires the backend service to keep track of the isPublished field on the post body and when that has flipped to true, start the publishing process. This feels a bit more complicated and more maintanence.
So my question is, is it OK from a REST standpoint to use the first approach? Are there some big downsides?
Upvotes: 1
Views: 2547
Reputation: 130917
Technically there's nothing that stops you from using verbs in the URL, following a RPC style. Conceptually that's not how REST is supposed to be designed.
REST stands for Representational State Transfer. This architectural style is resource-oriented and protocol independent but it is frequently implemented over the HTTP protocol.
When implementing REST applications over the HTTP protocol, a resource is identified by a URI and the operations over such resource are expressed by HTTP methods (any other verbs shouldn't be needed). To change the state of a resource, you should send to the server a representation of the new state of the resource. A representation can be a JSON, a XML or any other format capable to represent the state of the resource. See the quote below:
REST components perform actions on a resource by using a representation to capture the current or intended state of that resource and transferring that representation between components. A representation is a sequence of bytes, plus representation metadata to describe those bytes. Other commonly used but less precise names for a representation include: document, file, and HTTP message entity, instance, or variant.
[...] a given representation may indicate the current state of the requested resource, the desired state for the requested resource, or the value of some other resource [...]
Following this approach, the product
resource could have a status
sub-resource. According to your needs, the status
can have different values, such as draft
, published
, inactive
...
Then use PUT
to replace the state of the status
sub-resource with a JSON sent in request payload:
PUT /api/products/1/status HTTP/1.1
Host: example.org
Content-Type: application/json
{
"value" : "published"
}
Upvotes: 4