Implementing custom actions for your RESTful API

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.

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.

--

--

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
Guillaume Viguier-Just

Guillaume Viguier-Just

Développeur web et passionné de finances personnelles