How do you get a RESTful resource with something other than an ID?

There may be situations when I need to find an object by parameters other than ID. What is the right RESTful way to do this?

For example, I could find User on username and password , so strictly RESTful " GET /users/1 " will not work.

According to the Rails docs, this is a URL pattern for retrieving all instances of a resource: " GET /users ". I could add parameters to this: " GET /users?username=joe&password=topsecret ", but this will distort the official purpose of the GET request.

+4
source share
2 answers

"GET / users? Username = joe & password = topsecret", but this will distort the official purpose of the GET request. "

No, it does not pervert anything. This is an absolutely correct and RESTful way to do this, and it is the recommended way to get dynamic results in the http specification. REST does not care about what is in the url, only that it is unique. The URL of this page can be http: // 3f778a9b8a7c778696e for all kinds of REST architecture, if this is the only way to get there, and it doesnโ€™t lead anywhere else.

http defines the query string protocol for returning dynamic results. Given the current state of your database, the query string you give your application should always return the same result. Then it will be OPEN. URL aesthetics is a completely different issue from REST.

according to the REST architecture, the rules of a GET request are that it always returns the same results (or maintains the same results for sufficiently long periods of time, so caching works), and that GET has no side effects. GET should be idempotent (always return the same results, no matter how many times you call it), and do not lead to a change in the state of the system. That's all.

Of course, you do not need to use the request protocol. You can put parameters in slashes, between semicolons, or maybe base64 encoded GUIDs. It is entirely up to you if it follows these simple rules.

+12
source

A few keys don't calm down, right? Perhaps /users/[username]?password=secret . Also, you do not want to use a password here, but some kind of API key so that the URL looks like this:

/users/leethal?secret=da01930adfe82810092

To use the username instead of id, do the following:

 # controller @user = User.find_by_username!(params[:id]) # model def to_param username end 
+2
source

All Articles