I'm building out an API for web app that I've been working on for some time. I've started with the User model. The user portion of the API will allow remote clients to a) retrieve user data, b) update user information and c) create new users. I've gotten all of this to work, but it doesn't seem like its setup correctly. Here are my questions:
- Should the API endpoint be users or user? What's the best practice?
- I have to add the action to the end, which I would expect to be picked up instead by the request type so I don't have to specify it explicitly. How do I get my routes setup properly as not to have to include the method for protected actions?
Let me give some examples:
Get request for show - want it to work without the "show"
- curl -u rmbruno:blah http://app.local/api/users/show
Put request for update - want it to work without the "update"
- curl -X put -F 'user[forum_notifications]=true' -u rmbruno:blah http://app.local/api/users/update
Create - works with or without 'create' which is 开发者_StackOverflow社区what I want for all these actions
- curl -X post -F 'user[login]=mamafatta' -F 'user[email]=zzz@zzz.com' -F 'user[password]=12345678' http://twye.local/api/users/
How do I structure routes to not require the action name? Isn't that the common way to to RESTful APIs?
Here is my route for the API now:
map.namespace :api do |route|
route.resources :users
route.resources :weight
end
I'm using restful authentication which is handling the http auth in curl. Any guidance on the routes issues and best practice on singular versus plural would be really helpful.
Thanks! -A
Singular vs plural endpoints for restful APIs depends on the model you are returning. Your URL should describe that there can be multiple instances of the 'users' resource.
Your routes are set up correctly. The GET and PUT requests should be including the ID of the user in the endpoint, i.e.
curl -u rmbruno:blah http://app.local/api/users/1
See this answer for an overview of why rails creates these "convenience" urls for CRUD actions: Rails - Redundant RESTFUL Actions for map.resources? (new, create)
精彩评论