Implementing custom actions for your RESTful API
Article 11 in the series of “ Pragmatic decisions for your RESTful API”, this post talks about how to implement custom actions in your RESTful API. This article also updates this older blog post (and actually does not provide the same recommendation).
Implementing custom actions: use actions in the URL even if it’s not RESTful
Some actions do not fit in the CRUD world. Consider, for example, powering on or off a virtual machine, subscribing a user to a list or starring a product.
You could have the following endpoints:
Strictly speaking however, these endpoints are not RESTful, because they do not use nouns in their URLs, but action verbs.
Here are some possible options to overcome these issues and be as RESTful as possible:
Option 1: treat it as an attribute
For example, to power on or off a virtual machine, you could have a state attribute set to on or off. Turning it on would therefore become:
PATCH /machine/1{
state: "on"
}
Option 2: use resources instead
If it’s possible, you can use resource names instead of action verbs. For example, in the case of a user subscribing to a list, you could use a subscription sub-resource, such as for example: