Custom actions in your REST API

What are custom actions ?

Examples of custom actions are voting on a resource, subscribing to a service, starring or following a resource etc… basically any action which doesn’t fit in the CRUD world. While CRUD operations are fairly easy to handle restfully, custom actions do not fit so well in the REST paradigm, so how can we handle them “RESTfully”.

REST Principles

REST principles actually state that resources should be named with nouns, while an HTTP Verb (such as GET, POST, PUT or DELETE) should be used to describe an action on these resources. For example:

Action in the URL

The first idea I had was to add an action verb in the URL, to have something like:

Thinking RESTFUL: subscriptions

Instead of thinking in terms of actions, such as subscribing/unsubscribing a user to/from a list, RESTful tells us to think in terms of resources. When subscribing a user to a list, we are actually creating a subscription resource. The following 3 alternatives ARE RESTFUL, and the one you chose will actually depend on your underlying data model and where you want your subscriptions to be stored.

Option 1: subscriptions as a new resource type

This would be something like:

Option 2: subscriptions belonging to a user

This would be something along the lines of:

  • GET /users/12/subscriptions
  • POST /users/12/subscriptions
  • PUT /users/12/subscriptions/1
  • DELETE /users/12/subscriptions/1

Option 3: subscriptions belonging to a list

Here, we would have something like:

  • GET /lists/16/subscriptions
  • POST /lists/16/subscriptions
  • PUT /lists/16/subscriptions/1
  • DELETE /lists/16/subscriptions/1

--

--

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