3

使用 REST API 工作,遇到了一个问题,我想传递一个表示关系的值,但也传递该关系的 URL,以便它可以符合 HATEOAS。

我想我已经提出了一个合适的解决方案,但希望得到那些比我更有知识的人的确认。

这个 RESTful JSON 响应是否仍然符合 HATEOAS 原则?

{
  "employee":{
      "empId":12345,
      "fName":"Bubba",
      "lName":"Gump",
      "title":"Shrimp",
      "reportsTo":54321,
      "hateoas":{
          "self":"http://www.bubbagumpshrimp.com/rest/Employees/12345",
          "reportsTo":"http://www.bubbagumpshrimp.com/rest/Employees/54321",
          "directReports":"http://www.bubbagumpshrimp.com/rest/Employees/?reportsTo=12345"
      }
  }
}

那么大家怎么看呢?这种格式会起作用吗?

根据下面@fumanchu 的建议,这是我现在尝试使用的格式...

{
    "employee":{
        "empId":12345,
        "fName":"Bubba",
        "lName":"Gump",
        "title":"Shrimp",
        "reportsTo":54321,
        "hateoas":{
            "collection":"http://www.bubbagumpshrimp.com/rest/Employees/",
            "self":"12345",
            "reportsTo":"54321",
            "directReports":"12345/DirectReports"
        }
    }
}

谢谢指导!

4

1 回答 1

3

它“有效”,但它是多余的。一旦你有了 URI,为什么要保留那些与它们的语义或如何​​使用它们无关的裸 id?我建议你试试这个:

{
    "employee":{
        "self":"http://www.bubbagumpshrimp.com/rest/Employees/12345",
        "fName":"Bubba",
        "lName":"Gump",
        "title":"Shrimp",
        "reportsTo":"http://www.bubbagumpshrimp.com/rest/Employees/54321",
        "directReports":"http://www.bubbagumpshrimp.com/rest/Employees/12345/directReports"
    }
}

(没有理由将“directReports”资源公开为“?reportsTo=12345”。通过它的含义来识别它总是比通过它的实现来识别它更好。)

如果您可以控制您的 API 和/或媒体类型(并且您必须告诉您的客户期望 URI 的位置,因为 JSON 没有定义任何内容),您甚至可以通过声明“reportsTo”来缩短它,和 "directReports" 值是相对于 "self" 的 URI:

{
    "employee":{
        "self":"http://www.bubbagumpshrimp.com/rest/Employees/12345",
        "fName":"Bubba",
        "lName":"Gump",
        "title":"Shrimp",
        "reportsTo":"54321",
        "directReports":"12345/directReports"
    }
}
于 2012-02-14T01:31:00.497 回答