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:

POST /user/123/subscriptions

Option 3: use custom HTTP headers

Although this is something I’ve never used so far, you could also use a custom HTTP header instead to define your actions, if you have a resource which has lots of actions. For example, for a virtual machine:

POST /machine/1X-MyApi-MachineAction: "PowerOff"

Option 4: use actions in the URL anyways

If it’s not possible or not convenient to do otherwise, you can use actions in your URLs anyways. For example, if you need an endpoint which will search over multiple resources, it will probably make sense to call that endpoint /search.

My final advice on this point is that, unless you can find a smart way to remain RESTful without decreasing the readability and comprehensiveness of your API, you should probably use action verbs in your URLs, even if it’s not strictly RESTful. Just try to avoid using them too much.

If you want to read all of the articles of the series “ Pragmatic decisions for your RESTful API”, you can start here. The next article will focus on the implementation of webhooks in your RESTful API.

If you need it in a handy format, this series of articles is also available as an eBook on Amazon.

Originally published at on April 5, 2018.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store