How should a REST URL schema look like for a tree hierarchy?

前端 未结 5 816
Happy的楠姐
Happy的楠姐 2020-12-24 06:04

Let\'s assume that I have stores, shelves in a store, and products on a shelf. So in order to get a list of products on a shelf in a store, I\'d use the following request:

5条回答
  •  失恋的感觉
    2020-12-24 06:50

    Creating a product should just be a POST to

    http://server/product
    

    Updating a product should just be a PUT to

    http://server/product/$id
    

    Getting a product should just be a GET to

    http://server/product/$id
    

    Deleting a product should just be a DELETE to

    http://server/product/$id
    

    You should use the http methods that are there for you to get more functionality out of a simpler uri structure. If creating a product requires a passing in a store and shelf as a requirement, then those should get passed in the body of your POST (or PUT if you're changing shelves).

    When someone does a GET to http://server/product/$id, they will get back some kind of xml/json response, right? What does that look like? The incoming data for a create or update should be POSTed or PUT the same way in the body of the request. That is how you pass in the store and shelf, not via the uri. The uri should be as simple as possible and just point to the resource (product), using the http verbs to differentiate functionality.

    If you want to be able to get the contents of shelf 23, you do a GET to

    http://server/shelf/23
    

    When you do, you get back a json / xml / custom media type document that has the shelf data and a collection of product elements with links back to their product uri.

    If you want to be able to move product 23 from one shelf to another, you do a PUT to

    http://server/product/23 
    

    In the body of the PUT you have the product in the representation of your choice, but with the updated shelf.

    It's a weird mode of thinking at first, because you're not dealing with functionality across the entire system, but instead focusing on the resources (product, shelf, store) and using the http verbs to expose them to the universe.

提交回复
热议问题