过滤Rest API

时间:2017-07-12 13:08:52

标签: rest api api-design

我有两个实体' person'和'企业'并且它们都有子资源(例如位置)

所以我有端点:

GET /persons/{id}/locations
GET /businesses/{id}/locations

现在我想要一个端点来过滤主要资源的位置。 如果我这样做:

GET /persons/{id}/locations?country={...}
GET /businesses/{id}/locations?country={...}

我会搜索特定人/企业的位置。

过滤所有人的位置的最佳做法是什么 我有一些想法:

1. GET /persons/locations?country={...}   
2. GET /locations?entity=persons&country={...}

但不确定这些是好的。

1 个答案:

答案 0 :(得分:0)

您可以使用扩展概念,您可以将其与实体之间的关系一起使用。

GET /persons

{
  "data": [
      {"person_id": 1},
      {"person_id": 2}
 ],
 "links": [ 
    {
        "rel": "locations",
        "href": "/person/1/locations"
    },
    {
        "rel": "locations",
        "href": "/person/2/locations"
    } 
  ]
}

GET /persons?expand=locations&country={...}   

{
  "data": [
      {"person_id": 1, "locations": [...]},
      {"person_id": 2, "locations": [...]}
  ]
}