REST resource path design

后端 未结 2 1164
遇见更好的自我
遇见更好的自我 2020-12-18 05:51

I\'m developing a REST service, and I\'m trying to adhere to Doctor Roy Fielding\'s conventions and guidelines.

I picture my service as an endpoint that exposes a se

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 06:46

    I think this is the key comment:

    a product is associated with a brand.

    The word associated tells me you need to link resources together. So, let's say that there is an association between brands and products. Each resource has would have their own set of methods (GET, PUT, etc) as you described, but the representations should have links to other resources that describe their associations. Where the links are depends on the type of association (one-to-one, one-to-many, many-to-one, many-to-many) and direction.

    For example, let's say there is a canonical request for this product to api.example.com:

    GET /product/12345
    

    It returns some representation of that product. For simplicity, I am going to use XML for the representation, but it can be XHTML, JSON or whatever you need. So, a simple representation of product 12345:

    HTTP/1.1 200 OK
    Content-Type: application/xml; charset=utf-8
    Content-Length: ...
    
    
    
      Macaroni and Cheese
      
      
    
    

    As you can see, I am embedding links into the representation of product 12345 describing each relationship. Whenever possible, I try to follow HATEOAS constraint as much as I can:

    • There is explicit linking between the current resource and associated resources.
    • An optional relationship description ("rel"). "self" and "parent" are descriptions about the relationship the current resource and the resource the link references.
    • An optional preferred MIME type that should be requested. This describes the type of document that the client should expect if a followup request is made.
    • Opaque URLs instead of raw identifiers. Clients can just "navigate" to the URL without building them using some convention. Note that URLs do not always need to contain a unique database identifier or key (like "/brands/kraft").

    To expand on some advance concepts, let's say that products have other relationships. Maybe products have hierarchical relationships or products supersedes other products. All of these complex relationships can represented by links. So, an advanced representation of product 12345:

    HTTP/1.1 200 OK
    Content-Type: application/xml; charset=utf-8
    Content-Length: ...
    
    
    
      Macaroni and Cheese
      
      
      
      
              
    
    

    In this example, I am using "prev" and "next" to represent a chain of products. The "prev" can be interpreted as "superseded" and "next" be interpreted as "superseded-by". You can use "superseded" and "superseded-by" as rel values, but "prev" and "next" are commonly used. It is really up to you.

提交回复
热议问题