【问题标题】:Should I provide parent resource name in URL or not in RESTful WS?我应该在 URL 中提供父资源名称还是不在 RESTful WS 中提供父资源名称?
【发布时间】:2012-02-28 19:12:49
【问题描述】:

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

我有 2 个实体,假设 国家城市。我现在只是提供 WS 来获取、创建、更新或删除 cities,但 API 不支持通过 WS 进行 countries 操作。我正在使用 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 中的实体关系?”

【问题讨论】:

    标签: web-services rest restful-url


    【解决方案1】:

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

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

    { '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”关系,现在可以提供/cities/612 上的GET

    { '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',
            ...
        },
        ...
      }
    }
    

    查看A RESTful Hypermedia API in Three Easy Steps了解更多详情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      相关资源
      最近更新 更多