Should I provide parent resource name in URL or not in RESTful WS?

左心房为你撑大大i 提交于 2019-12-04 18:36:52

'How should I handle entities relationship in API urls?' Don't. Instead use links in the resources you respond with.

For instance, if I do a GET on /cities/612 I might get back

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

This allows you to have any entity relationship you like, without having to worry about your URLs. You can alos easily add new relationships without breaking existing clients. For instance, if you wanted to add a new relationship of 'planet', GET on /cities/612 might now provide

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

Have a look at A RESTful Hypermedia API in Three Easy Steps for more details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!