开发者

RESTful design of URLs for widgets owned by users

开发者 https://www.devze.com 2023-02-15 20:05 出处:网络
My RESTful API always has authentication so all calls are authenticated for a particular user. Which is a better RESTful design of URLs over the HTTP protocol?

My RESTful API always has authentication so all calls are authenticated for a particular user.

Which is a better RESTful design of URLs over the HTTP protocol? Remember that the user id 3 is already authenticated via basic http auth/digest.

http://server.com/users/3/widgets/ (Returns all widgets for user id 3)

http://server.com/users/3开发者_开发知识库/widgets/13 (Returns widget id 13)

or:

http://server.com/widgets/ (Returns all widgets for user id 3)

http://server.com//widgets/13 (Returns widget id 13)

Is it better to always have a unique URL like http://server.com/users/3/widgets/ even know only user #3 will be the only one accessing it? Is it redundant to re-specify /user/3 on every call like http://server.com/users/3/widgets/


I would definitely recommend the first option. If you choose the second and at some point you decide you want to allow caching then you would have to make sure that your vary header specified that the representation varies on the authorization header. This can be a pain if you use auth tokens that expire.

It also means that if you ever want to allow users to see the widgets of other users, you can and the caching would still work.


REST technically should be stateless, so the more "proper" implementation would be the first way you listed.

However, I would do things slightly differently than how you're suggesting for the first method--will the information a user gets back about a specific widget change, depending on the user? If not, you might want to try this:

http://server.com/users/3/widgets/ (Returns all widgets for user id 3)
http://server.com/widgets/13 (Returns widget id 13)

Gets a best of both worlds. Proper "REST-ful" implementation, but when it comes to specific widgets, the current user doesn't matter. This way, your clients could pass around queries for individual widgets more easily as well--without having to update the query themselves. If the client shouldn't have access to view that particular widget, that shouldn't be difficult to protect against with the authentication you have already.

I'm also basing this all off an assumption that the widget listing could differ from client to client--if that is not true, and all clients are going to see the same widget listing regardless, there's no reason to pass the user, so go with the second way.


I'd go with the first because that does fully specify the resource.

0

精彩评论

暂无评论...
验证码 换一张
取 消