REST URIs and operations on an object that can be commented on, tagged, rated, etc

后端 未结 7 2031
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-06 08:22

I\'m doing research into a web API for my company, and it\'s starting to look like we might implement a RESTful one. I\'ve read a couple of books about this now (O\'Reilly\'s \"

7条回答
  •  粉色の甜心
    2021-02-06 08:43

    Most of what you have looks good. There were just a couple of strange things I saw. When I put my URLs together, I try to follow these four principles.

    Peel the onion

    If you make the R in REST really be a resource then the resource URL should be able to be peeled back and still be meaningful. If it doesn't make sense you should rethink how to organize the resource. So in the case below, each makes sense. I am either looking at a specific item, or a collection of items.

    /movies/horror/10/
    /movies/horror/
    /movies/
    

    The following seems funny to me because flag isn't a resource, it's a property of the movie.

    /movies/5/comments/8/flag -> Funny
    /movies/5/comments/8/     -> Gives me all properties of comment including flag
    

    Define the View

    The last peice of the URL describes how to show the resource. The URL /movies/horror/ tells me I will have a collection of movies refined by horror. But there might be different ways I want to display that collection.

    /movies/horror/simple
    /movies/horror/expanded
    

    The simple view might just be the title and an image. The expanded view would give a lot more information like description, synopsis, and ratings.

    Helpers

    After the resource has been limited and the proper view figured out, query string parameters are used to help the UI with the little stuff. The most common query string parameters I use are

    p => Page
    n => number of items to display
    sortby => field to sort by
    asc => sort ascending
    

    So I could end up with a URL like

    /movies/horror/default?p=12&n=50&sortby=name
    

    This will give me the list of movies limited to horror movies with the default view; starting on page 12 with 50 movies per page where the movies are sorted by name.

    Actions

    The last thing needed are your action on the resource. The action are either collection based or item based.

    /movies/horror/
    GET -> Get resources as a list
    POST -> Create, Update
    
    /movies/horror/10/
    GET -> Get resource as item
    POST -> Update
    

    I hope this helps.

提交回复
热议问题