Best way to implement a RESTful toggle-action?

I am doing a rewrite of an old Rails application, and I thought I should do it with RESTful, like a learning experience, if nothing else.

I have achieved some actions that switch the boolean value, for example, if the article is published or not.

Before I had a few actions: toggle_published, publish and cancel the publication.

They were very easy to use: I just made a link to them in the list of articles.

How would you do the same in RESTful?

Should I use the update-action and create a mini form to replace every link I used before? I do not particularly like this idea.

+7
rest ruby-on-rails
source share
3 answers

It looks like you have two use cases:

  • set published state
  • switch published state

You should be able to add a member route for the switching action for:

/articles/<id>/toggle_published - calls Article.toggle(:published) 

And use the article update: published attribute via the standard REST resource route.

 map.resources :articles, :member => :toggle 
0
source share

Just a notice:

The toggle method is not RESTful because the HTTP PUT verb must be idempotent (see ao http://en.wikipedia.org/wiki/Idempotence#Examples ). This means that no matter how often you execute the method, it should always give the same result. The toggle method does not adhere to this principle, since it does not give the same result if you performed it once compared to executing it twice.

If you want to do this RESTful, you must create two methods: one for customization and one for undo.

Creating a RESTful application does not only mean that you must use the correct HTTP verb.

+23
source share

I would probably solve it using PUT / DELETE or POST / DELETE on a nested "switch resource". It may not be 100% completely soothing, but certainly light enough to understand.

 PUT or POST /articles/:id/published # Toggle published ON DELETE /articles/:id/published # Toggle published OFF GET /articles/:id/published # Get state RESTfully via status 200 (ON) or 404 (OFF) 

It may seem a little strange, but it is technically RESTful.

Update: Perhaps a more natural approach might be:

 PUT or POST /articles/:id/published Data: { state: true/false } # Toggle published ON 

You can also use the verb PATCH with an actual article, which I assume has a published property:

 PATCH /articles/:id { published: true/false } 

Because all the cool REST kids use PATCH these days.

+9
source share

All Articles