Different REST representations of same resource fo

2019-05-26 04:05发布

问题:

I have a simple resource something like this:

/api/{configuration}/exhibitors/{id}

This is generally a public API depending on the setup of the configuration part of the URL.

It might return this to a non authenticated user:

{ "a" : "some value", "b" : "other value" }

But if an administrator was logged in and wanted to get this resource, they'd expect some slightly different data on that same resource:

{ "a" : "some value", "C" : "admin only value" }

Should I be detecting this admin authority and just return different content from the same URL?

Or should I have a new URL that identifies who it is for and that the content might be different?

/api/admin/{configuration}/exhibitors/{id}

My thinking is that I don't like the extra URLs, but I'll more easily be able to cache the public content if I do not potentially change the content depending on the user.

There is no reason that the admin call can't get the full public version of the resource plus the additional admin only fields, but they probably don't actually need field "b" in my example, so I'd rather the admin representation was a bit lighter.

回答1:

Depending on the situation, both options are viable. As you mention, allowing variations in the representations will make caching difficult. However, there is extra overhead in supporting different resources. Ideally your server side framework makes it easy to create additional resources, so the overhead should be minimal.

The other option is return the public version and provide an embedded hyperlink to a resource that contains just the additional "admin-only" properties. If your clients can deal easily with hypermedia, that becomes a fairly flexible option.



回答2:

I imagine an authenticated user would be someone who has provided user id and a password, i.e. logged in. After a user has logged in, most REST apps tend to rely on a cookie to determine if the request is from an authenticated user or not.

Ideally, each user should have its own context. One user's /tmp/foo is different from another user's /tmp/foo. You can still have public content that is identified by a URL beginning with /public or something similar.

For security reasons, you really do not want to divulge the user's id as part of the URL. Also, the user id often tends to be user's email or account number.

Admin is a special case and depending on the back-end architecture, it is possible to implement a solution that allows admin to access other user's administrative info.



标签: rest