简体   繁体   中英

Permissions to a nested resource in REST API

Background

Consider having 3 resources: reports , comments and attachments . The report can have many comments , and the comment can have many attachments .

Additionally, attachments which are attached to a specific report (in the report -> comment -> attachment tree) can only be reached by users who have permission to the specific report .

Question

Now, I'm a fan of flat URL structures while designing REST APIs, but in the case above I have no idea how could I do this without creating a very long resource like:

/reports/:id/comments/:id/attachments/:id

Is there any way to meet these requirements (permissions) and be able to reach the attachment from a flat URL like /attachments/:id ?

or maybe I'm exaggerating and it's totally ok to have these kinds of long resource URLs?

Disclaimer: I've created an attachments resource (and not report-attachments ) because there are other resources which also need to have attachments - I didn't want to duplicate the structure.

it's totally ok to have these kinds of long resource URLs?

It's totally ok to have any kind of resource URLs. REST doesn't care how you spell your resource identifiers -- that's kind of the point. So if you need a log URL because the server needs to encode a lot of information into it, that's fine.

If you are worried about length, you can strip down the semantic hints

/reports/:id/comments/:id/attachments/:id
/reports/:id/c/:id/a/:id
/reports/:id/:id/:id
/:id/:id/:id

Some of these spellings will be easier for the routing framework that you are using on the server, but that's an implementation detail that you control.

There's no rule that says that you have to have the information encoded directly into the identifier; URL shorteners work .

In HTML, we also have the ability to construct (some) identifiers from information provided by the client, via a form. That's because the definition of the HTML media type includes processing rules that describe how the form data is assembled into an application/x-www-form-urlencoded representation that is included in the query part.

So you can introduce a similar mechanism into your own media types.

There's also RFC 6570 , which describes URI templates. That gives you another way to communicate with the client how to encode information into a URL.

Is there any way to meet these requirements (permissions) and be able to reach the attachment from a flat URL like /attachments/:id?

Sure. You just need to be able to use :id to look up / calculate the correct permission set, then check the request to see if the permissions are satisfied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM