这种RESTful JSON响应格式是否符合HATEOAS?

时间:2012-02-13 18:13:05

标签: json rest hateoas

使用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"
        }
    }
}

感谢您的指导!

1 个答案:

答案 0 :(得分: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"
    }
}