2

我正在使用 PHP 和 apache 开发一些基本的 RESTful Web 服务,我想知道是否应该构建提供父实体名称的 URL。让我更好地解释一下:

我有 2 个实体,假设国家城市。我现在只是提供 WS 来获取、创建、更新或删除城市,但 API 不支持通过 WS 进行国家/地区操作。我正在使用mod_rewrite重新映射 url ,并在 api 中提供以下 url 来操作城市:

. GET     /api/countries/<country_id>/cities            cities of country with id <country_id>

. GET     /api/countries/<country_id>/cities/<city_id>  city with id <city_id>

. POST    /api/countries/<country_id>/cities            add a city to country with id <country_id>

. PUT     /api/countries/<country_id>/cities/<city_id>  update the city whose country has id <country_id>

. DELETE  /api/countries/<country_id>/cities/<city_id>  delete city ...

我开始仔细查看这些 url,我很困惑是否应该提供父实体名称和 id。我做了一个很好的假设,城市不能分配到一个以上的国家,即它不是多对多的关系。假设这一点,我认为可以为许多 API 函数提供更短的 URL 模式。例如,如果客户想要删除某个城市,发送以下内容就足够了:

. DELETE /api/cities/14

我知道一个城市属于一个国家,客户端在发出请求之前不需要找出国家ID。

除了第一个(获取所有国家/地区的城市)之外,大多数 url 都可以转换为这种较短的 url。

这是我第一次开发 Web 服务,我没有阅读太多关于它的内容,所以我可能会误解一些东西。我能得到一些建议吗?非常感谢,对我的初级英语感到抱歉。

EDIT1:我认为这个问题可以概括为“我应该如何处理 API url 中的实体关系?”

4

1 回答 1

3

“我应该如何处理 API url 中的实体关系?” 不。而是在您回复的资源中使用链接。

例如,如果我执行 GET 操作,/cities/612我可能会返回

{ 'city': 
  {
    'id': 612,
    'self': '/cities/612',
    'name': 'Sydney',
    'country': { 'name': 'Australia', 'href': '/country/61' },
    'region': { 'name': 'Asia Pacific', 'href': '/region/12' },
    'delete': {
      'method': 'delete',
      'href': '/cities/612'
    },
    'update': {
      'method': 'put',
      'href': '/cities/612',
        ...
    },
    ...
  }
}

这使您可以拥有任何您喜欢的实体关系,而不必担心您的 URL。您还可以轻松地添加新关系,而不会破坏现有客户。例如,如果你想添加一个新的 'planet' 关系,GET on/cities/612现在可能会提供

{ 'city': 
  {
    'id': 612,
    'self': '/cities/612',
    'name': 'Sydney',
    'country': { 'name': 'Australia', 'href': '/country/61' },
    'region': { 'name': 'Asia Pacific', 'href': '/region/12' },
    'planet': { 'name': 'Earth', 'href': '/planet/1' },
    'delete': {
      'method': 'delete',
      'href': '/cities/612'
    },
    'update': {
      'method': 'put',
      'href': '/cities/612',
        ...
    },
    ...
  }
}

了解更多详细信息,请查看三个简单步骤中的 RESTful 超媒体 API 。

于 2012-02-29T06:38:44.330 回答