Best way to implement a RESTful toggle-action? - ruby-on-rails

I'm doing a rewrite of an old Rails application and I thought I should do it in a RESTful manner, as a learning experience if nothing else.
I've reached some actions that toggles a boolean value, for example if an article is published or not.
Before I had a couple of actions: toggle_published, publish and unpublish.
They were very easy to use: i just made a link to them in the article-list.
How would you do the same thing in a RESTful manner?
Should I use the update-action, and build a mini-form to replace each link that I used before? I don't particulary like that idea.

Just a notice:
A toggle method is not RESTful, because the HTTP PUT verb is supposed to be idempotent (see a.o. http://en.wikipedia.org/wiki/Idempotence#Examples). This means that no matter how often you execute a method, it should always give the same result. A toggle method does not adhere to this principle, as it does not give the same result if you execute it once comparing to executing it twice.
If you want to make it RESTful, you should create two methods: one for setting and one for unsetting.
Making an application RESTful does not only mean that you should use the correct HTTP verb.

I'd probably solve it with PUT/DELETE or POST/DELETE on a nested "toggle resource". Perhaps not 100% completely restful but certainly easy 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)
Might seem a bit odd, but it is technically RESTful.
Update: A (perhaps) more natural approach might also just be:
PUT or POST /articles/:id/published Data: { state: true/false } # Toggle published ON
You could also use the PATCH verb with the actual article which I assume has a published property:
PATCH /articles/:id { published: true/false }
Because all the cool REST kids are using PATCH nowadays.

It sounds like you have two use cases:
set published state
toggle published state
You should be able to add a member route for the toggle action for:
/articles/<id>/toggle_published - calls Article.toggle(:published)
And use Article update on :published attribute via the standard REST resource route.
map.resources :articles, :member => :toggle

I like #Van der Hoorn answer
so in real life we are using in login & logout scenario
use post or put or patch
/users/login -> with some payload data
/users/logout
In Above Eg login & logout is almost acting like setting boolean Flag , Easy to read and set in db
Eg : so its no harm to use same idea in toggle context
use post or put or patch
/book/3/publish
/book/4/unpublish
Note . :
1 : use this approach if there is only 1 field to be toggled , else if there are multiple fields then general /book/4 a patch request with payload data will do
2 : use this approach if there is any security layer is implemented so it will be like
Eg :
Editor -> can access urls like `/books/:id` & `/books/:id/publish`
Senior Editor -> can access urls like `/books/:id` & `/books/:id/unpublish`

Related

Put or patch for new update action Rails

I want to add a new update(new_update) action in my user model of rails which will update a single column in the model. which rest api method I should use in routes file. Should I use put or patch or both.
resources: users do
member do
put 'new_update'
patch 'new_update'
end
If you want to match 100% with the HTTP verb definition.
PUT is supposed to overwrite your targeted resource entirely with the content in the request(all field non present in the request should be set to removed/nullified).
PATCH is supposed to only modify the fields sent in the request.
That being said, most of the time people don't make the difference and use either of them (a lot of people don't even know that there is a PATCH verb) is use PUT with the same behavior as PATCH (since the use case for PUT is quite rare on imo).

RESTful method for representing a has_one relationship with no identifier

I currently have a service with a REST API which is pretty standard:
show: GET /users/1
update: PUT /users/1
...and some has_many relationships which follow the same convention:
show: GET /users/1/friends/1
update: PUT /users/1/friends/1
However, there is also an EAV table to handle settings (sorry, this part isn't going to change), set up to act as a has_one relationship. Internally:
user.settings # returns {:sound => true, :tutorials => true}
user.update_settings # expects {:sound => false}
It works well locally, but there's no ID to represent it the way the other routes work. Instead, the routes could be set up like this:
show: GET /users/1/settings
update: PUT /users/1/settings
Is this a normal way to handle this, or is there some other convention I'm not aware of?
Well, if you do not need an Id to access the settings, why not treat it as an attribute of the collection? Internally it's the same to you, just close the /users/:id/settings endpoint. And GET and UPDATE the user resource to change settings. The user would look somthing like this:
{ "id" : 12,
"settings": {
...
}
}
If you think of settings an attribute, the enpoint does not seem grammatically correct. Imagine you posed the same question regarding age of the user. Would you open a /user/:id/age endpoint? Is it all that the settings has more attributes? where to stop then? Again a matter of concepts and above all CONSISTENCY.
But don't be a REStafarian. Your approach is also good. For me is much more a matter of consistency so that you dont have to write tons of doc for your developers explaining exceptions. So make your choice taking into account what fits best with the rest (i'd go for my suggestion).
Be pragmatic!

Routing without the model name

Using this question and railscast 63 I've got my articles routed to articles/article_permalink.
I'd like them to be accessible without the model name in the url so my-domain.com/article_permalink routes directly to the article. I'd only want this to happen on the show action. Is this possible?
I think you need something like ...
(in routes.rb)
match '/:id' => 'articles#show', :via => 'get'
(needs to be last, or towards the end of the routes as it can match requests intended for other routes)
To change the article_path(...) helpers, "as" might help: http://guides.rubyonrails.org/routing.html#overriding-the-named-helpers
Or you can add a helper for that specific path.
If I understand your question, you want the model tied to the route "articles/article_permalink" to be dynamic based upon which is article is selected from a list?
Would you be open to appending a model ID to the end of the URL as a query string? A more complicated approach would be to have your links POST, with the model ID as a hidden input field. Your controller could determine if it was accessed via get/post, and handle it accordingly, but that doesn't feel right.
Regardless, when the controller action is fired up based upon a request to "articles/article_permalink", it has to know which model to fetch. With HTTP being stateless, something has to be passed in. You could get fancy and write JavaScript to fire one AJAX call, set a session var, and then fire the GET, but that's messy.
I hope I understood the question...

Non-CRUD Controller Actions

This might seem like a n00b question, but I am trying to break some of my bad practice that I may have adopted using MVC, so I hope you can help me out
So, imagine I want to do something like "Upload CSV And Parse It", it doesn't seem obvious to me to fit it into the CRUD pattern... I am not interacting with the DB, so i don't need add or update or delete, but I still want to be able to use the action in a meaningful way from different views. Thus, it is "ok" to just an action called "UploadCSV" and have it be accessible via a URL such as "/data/uploadcsv"
Your thoughts are much appreciated!
Tom
It sounds like you are talking about RESTful ideas (having actions called index, create, new, edit, update, destroy, show).
In MVC you can call an action largely whatever you want (so yes, you can call it uploadcsv if you want). If you want it fit RESTful principles you might want to think about what the action is doing (for example is a data upload essentially a create or an update function) and name it using one of the RESTful action names.
I believe I have the same point of view as you.
In my projects I try to be as restful as possible whenever I can. However as you said sometimes a special case just does not 'fit'
After all it is also a question of 'feeling'
If you provide a csv import function, I see it as perfectly correct to not create a full REST implementation for CSV.
Let's imagine in your application you have clients. And you wnat to give the option for clients to import data using csv. You can add a route for this action using:
map.resources :clients, :member => { :uploadcsv => :get }
The route is properly declared, Your 'clients' resource is completely restful and you have an additional action properly declared to manage data importation.
The only warning I have is: don't use a route like this one "/data/uploadcsv". From my point of view It lacks clarity. I like to be able to understand what my application is going to do just be looking at the url. And '/data' is too vague for me :)
The persistence of the resource is not crucial here. I suppose that what you are doing here is this - creating some kind of resource (although not persistent) out of the csv provided. The thing here is to think about what this csv file represents. What's inside? Is it something that will become a collection of resources in your system, or is it a representation of only one object in your system? If you think about it it has to be something concrete. Can you be more specific about your problem domain?

Why use HTTP PUT and DELETE methods instead of POST?

new_story GET /story/new(.:format) {:action=>"new", :controller=>"stories"}
edit_story GET /story/edit(.:format) {:action=>"edit", :controller=>"stories"}
story GET /story(.:format) {:action=>"show", :controller=>"stories"}
PUT /story(.:format) {:action=>"update", :controller=>"stories"}
DELETE /story(.:format) {:action=>"destroy", :controller=>"stories"}
POST /story(.:format) {:action=>"create", :controller=>"stories"}
In web development I have done with other technologies, I only ever used GET and POST methods, but with RESTful routes in Rails, by default the PUT and DELETE methods are used for the update and destroy actions. What's the advantage or need for using PUT and DELETE? I assume these methods are just another way of doing POST - but why not just stick with POST?
The advantage is mostly semantic, and can also simplify URLs to an extent. The different HTTP methods map to different actions:
POST => create a new object
DELETE => delete an object
PUT => modify an object
GET => view an object
Then, in theory, you can use the same URL, but interact with it using different methods; the method used to access the resource defines the actual type of operation.
In practice, though, most browsers only support HTTP GET and POST. Rails uses some "trickery" in HTML forms to act as though a PUT or DELETE request was sent, even though Rails is still using GET or POST for these methods. (This explains why you might not have used DELETE or PUT on other platforms.)
I just wanted to add something to the accepted answer because his definition of the http verbs are incorrect. They all have a spec which "should" be followed and you can create/update/delete with multiple http verbs based on the specs.
I am going to highlight some of the important bits in the RFC 2616 by W3
I'm going to start with PUT because in my opinion it has the most confusion surrounding it.
PUT is used for both create/update PUT updates by completely replacing the resource on the server with the resource sent in the request
For example
You make this call to my api
PUT /api/person
{
Name: John,
email: jdoe#hra.com
}
my Server has this resource living on the server
{
Name: Jane,
email: jdoe#hra.com
}
Now my existing resource is completely replaced by what you sent over and this is what I have on my server.
{
Name: John,
email: jdoe#hra.com
}
So if you PUT and only send an email in the body
PUT /api/person
{
email: jdoe#hra.com
}
My Server will completely replace the entity
{
Name: Jane,
email: jdoe#hra.com
}
With
{
email: jdoe#hra.com
}
And Name will be gone. Partial updates are for PATCH but I use POST for that anyway.
One of the main reasons why we create/update with put is because it is idempotent.
It's just a fancy term and the basic definition of it is multiple identical requests are the same for a single request.
Example
Suppose I PUT a file to api/file if the origin server does not find that file it will create one. If it does find a file it will completely replace the old file with the one I sent over. This ensures that one file is ever created and updated. If no file exists and you call PUT 5 times, the first time it creates a file then the other 4 times it replaces the file with what you send over. If you call a POST 5 times to create it will create 5 files.
You PUT to that exact URI. If you don't you have to send a 301 (Moved Permanently) to the user and allow then make a choice whether or not to redirect the request. Most times the server you PUT to usually hosts the resource and takes care of updating it
Those are the major points in when to use PUT
As far as POST is concerned
You can also create/update and then some...
As I mentioned above there are a few key differences.
Post is more General. In what ways? some other examples include a gateway to other protocols, it could take the response and send it to some data handler out in the middle of yonder, or it can extend some sort of functionality.
Post doesn't have the restriction of "To the exact URI or notifiy" for examplePOST can append a resource to an existing collection and decide where it's stored.
Now what about Delete Why don't I just POST?
When you DELETE, the server SHOULD NOT respond with success unless you delete the resource or move it to an inaccessible location at the time the response is sent.
Why is that important? What if you call DELETE but the resource has to go through "APPROVAL" before being deleted? If the delete can be rejected you can't send a successful error code and if you do follow the basic specs on this it's confusing to the caller. Just an example I'm sure you can think of many others.
I just highlighted some of the major points on when to use the common Http verbs
Here's the "methods" section of the HTTP 1.1 spec; it defines lots of methods, and they all have different benefits and tradeoffs. POST is the most flexible, but the tradeoffs are numerous: it's not cacheable (so the rest of the internet can't help you scale), it isn't safe or idempotent so the client can't just resend it gets an error, and it is no longer clear exactly what you're trying to accomplish (because it's so flexible). I'm sure there are others but that ought to be sufficient. Given all that, if the HTTP spec defines a method that does exactly what you want your request to do, there's no reason to send a POST instead.
The reason POST is so common is that, historically at least, web browsers only supported GET and POST. Since GET is defined to be safe and idempotent (even though many applications don't adhere to that), the only safe way to modify data was to send a POST. With the rise of AJAX and non-browser clients, that is no longer true.
BTW, the mapping #mipadi gave is the standard mapping, but it isn't the only valid one. Amazon S3, for instance, uses PUT to create resources. The only reason to use POST is if the client doesn't have sufficient knowledge to create the resource, e.g., you back your resources with a relational database and use artificial surrogate keys.
That'd be kind of like asking why "delete" a file when you could just set its contents to zero bytes and the file system would just treat that as a delete. HTTP has supported verbs other than GET/POST forever but the way SOAP evolved kinda twisted the original meaning of those verbs. REST is a simpler, back to basics approach that uses the verbs as they were intended instead of inventing some new verb concept inside of the payload.

Resources