How to construct URIs for RESTful service that operates tree-like data?
Assume I have tree-like data, e.g. “files” and “folders”, basic operations are “list folder”, “create folder”, “rename”, “create file”, “fetch file”.
So how can I construct URIs for RESTful service? I've tried a few times but all solutions look not very nice to me.
For example, if I have “folder” resource referenced by URI `http://example.com/rest/here_path_to_folder, how can I list folder items? Fetch “file” from this folder?
I've seen Amazon AWS docs, they are using not very clean approach—passing “folder” path and folders delimiter as query arguments, this could cause ambiguity because different URIs will reference the same resource. Also I've tried appending keywords to the end of path, so listing “files” looked like:
GET /rest/path/to/folder:list HTTP/1.1
Rename:
POST /rest/path/to/folder:rename?target=NEW_NAME HTTP/1.1
But it still look terrible for me. So do you know any success stories of using 100% REST on hiera开发者_StackOverflow社区rchial data?
I think it should be quite simple to use URIs to represent your hierarchical data structure. Although URIs don't strictly imply hierarchy (some people like to keep then completely opaque), meaningful URIs do have a naturally hierarchical feel and they should map nicely to your file/folder example.
In a RESTful system, resources have a common interface which (in your case) is defined by the HTTP verbs. The URI identifies a resource, REST dictates that it shouldn't be used to indicate the operation you are trying to perform.
So instead of
GET /rest/path/to/folder:list HTTP/1.1
I'd propose that to list the contents of a folder (find out it's state) you simply use:
GET /rest/path/to/folder HTTP/1.1
This should return a list of URIs which represent the files and subfolders that this folder contains. Then to get the contents of one of the files, I might then invoke:
GET /rest/path/to/folder/myfile HTTP/1.1
Renaming is a bit more tricky. In some cases a DELETE
followed by a PUT
would work, but I'm guessing you want to retain the folder contents without having to re-upload. One option is a PUT
where the body contains a new folder path, which responds with a 204 and the Location header value pointing to the newly created folder (as described in 'Renaming a tag' here). Optional: If you want to be really friendly to your users, you could also return a 301 status (Moved permanently) with a link to the new URI if the anyone makes a request to the old URI.
Remember the path is just one of the properties that makes up the state of a folder, you can update that state with PUT
without needing to introduce a custom 'rename' operation. In your case, you happen to use the path to decide your URI, but it's perfectly valid for a state change to cause a change in the URI.
精彩评论