【发布时间】:2018-06-05 02:51:33
【问题描述】:
想象一个 REST 端点 (/employees) 以 JSON HAL 格式提供员工页面。
一名员工居住在一个国家,该国家位于一个大陆。
对于国家和大洲,也有单独的端点。
返回的页面包含典型的_embedded 字段以及员工数据。
员工资源还包含嵌套的 country 资源。
这个嵌套的country 资源还包含_links。
在这种情况下,输出将是:
GET /employees
{
"_embedded": {
"employees": [{
"employee_id": 1
"name": "Mr. X",
"place_name": "London",
"country": {
"alpha2_code": "AU",
"name": "Australia",
"continent": {
"code": "OC",
"name": "Australia",
"_links": {
"self": {
"href": "http://localhost:8077/continents/au"
}
}
},
"_links": {
"self": {
"href": "http://localhost:8077/countries/au"
}
}
},
"_links": {
"self": {
"href": "http://localhost:8077/employees/1"
}
}
},
{
..
}
]
},
"_links": {
"first": {
"href": "http://localhost:8077/employees?page=1&size=10"
},
"self": {
"href": "http://localhost:8077/employees"
},
"next": {
"href": "http://localhost:8077/employees?page=2&size=10"
},
"last": {
"href": "http://localhost:8077/employees?page=8&size=10"
}
},
"page": {
"size": 10,
"total_elements": 71,
"total_pages": 8,
"number": 0
}
}
是country 的嵌套(以及continent 在country 中的嵌套,是否按照 HAL 规范以正确的方式输出。
在其他一些示例中,我注意到以下格式:
{
"_embedded": {
"employees": [{
"employee_id": 1
"name": "Mr. X",
"place_name": "London",
"_embedded": {
"country": {
"alpha2_code": "AU",
"name": "Australia",
"_embedded": {
"continent": {
"code": "OC",
"name": "Australia",
"_links": {
"self": {
"href": "http://localhost:8077/continents/au"
}
}
},
}
"_links": {
"self": {
"href": "http://localhost:8077/countries/au"
}
}
}
},
"_links": {
"self": {
"href": "http://localhost:8077/employees/1"
}
}
},
{
..
}
]
},
"_links": {
"first": {
"href": "http://localhost:8077/employees?page=1&size=10"
},
"self": {
"href": "http://localhost:8077/employees"
},
"next": {
"href": "http://localhost:8077/employees?page=2&size=10"
},
"last": {
"href": "http://localhost:8077/employees?page=8&size=10"
}
},
"page": {
"size": 10,
"total_elements": 71,
"total_pages": 8,
"number": 0
}
}
更新:第二个示例现在也清楚地表明它是分页响应。
它使用嵌套的_embedded 资源。
从规范的角度来看,有没有一种方法比另一种更好?还是两者都有效?
【问题讨论】:
标签: json rest domain-driven-design hal hypermedia