且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何模型继承一个RESTful API?

更新时间:2023-11-30 13:12:34

我建议:


  • 使用每个资源只有一个URI

  • 在属性级别的动物之间的区别仅仅

多个URI设置为相同的资源从来都不是一个好主意,因为它可能会导致混乱和意外的副作用。鉴于此,你的单身URI应基于像普通的方案 /动物

Setting up multiple URIs to the same resource is never a good idea because it can cause confusion and unexpected side effects. Given that, your single URI should be based on a generic scheme like /animals.

与狗和猫的整个集合处理在基地级别的下一个挑战已经凭借 /动物 URI的方式来解决。

The next challenge of dealing with the entire collection of dogs and cats at the "base" level is already solved by virtue of the /animals URI approach.

专门的类型,如狗和猫打交道就可以轻松解决使用中的查询参数和标识组合的最后一个挑战你的媒体类型中的属性。例如:

The final challenge of dealing with specialized types like dogs and cats can be easily solved using a combination of query parameters and identification attributes within your media type. For example:

GET /动物接受:应用/ vnd.vet-services.animals + JSON

{
   "animals":[
      {
         "link":"/animals/3424",
         "type":"dog",
         "name":"Rex"
      },
      {
         "link":"/animals/7829",
         "type":"cat",
         "name":"Mittens"
      }
   ]
}


  • GET /动物 - 得到所有狗和猫,会同时返回雷克斯和手套

  • GET /动物类型=狗 - ?得到所有的狗,只会返回雷克斯

  • GET /动物类型=猫 - ?得到所有的猫,那只手套

    • GET /animals - gets all dogs and cats, would return both Rex and Mittens
    • GET /animals?type=dog - gets all dogs, would only return Rex
    • GET /animals?type=cat - gets all cats, would only Mittens
    • 然后创建或修改的动物时,这将是对呼叫者责任指定动物所涉及的类型:

      Then when creating or modifying animals, it would be incumbent on the caller to specify the type of animal involved:

      介质类型:应用程序/ vnd.vet-services.animal + JSON

{
   "type":"dog",
   "name":"Fido"
}

以上的有效载荷可以用 POST PUT发送请求。

以上方案让你的基本相似的特性OO继承通过REST,并在没有重大手术或您的URI方案的任何变化进一步增加专业(即更多的动物种类)的能力。

The above scheme gets you the basic similar characteristics as OO inheritance through REST, and with the ability to add further specializations (i.e. more animal types) without major surgery or any changes to your URI scheme.