分层 RESTful URL 设计 [英] Hierarchical RESTful URL design

查看:45
本文介绍了分层 RESTful URL 设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经仔细阅读了有关此问题的问题,但我仍然没有明确的答案.

I have perused the questions asked about this, but I still don't have a definitive answer.

我有一个应用程序,想构建一个 RESTful API 来公开信息的子集.我有三个资源:

I have an application and would like to build a RESTful API to expose a subset of information. I have three resources:

  1. 用户
  2. 报告
  3. 照片

用户有报告,报告有照片.照片不能存在于报告之外,报告不能存在于用户之外.

Users have reports and reports have photos. Photos cannot exist outside of reports and reports cannot exist outside of users.

我根据自己的要求设计了以下网址

I have designed the following URLs for my requirements

用户登录,服务器以所有 API 调用头中发送的令牌响应

GET example.com/api/

获取用户信息

GET example.com/api/users/{username}

获取所有用户报告

GET example.com/api/users/{username}/reports

获取报告的所有照片

GET example.com/api/users/{username}/reports/{report_id}/photos

添加照片

POST example.com/api/users/{username}/reports/{report_id}/photos

删除照片

DELETE example.com/api/users/{username}/reports/{report_id}/photos/{photo_id}

修改照片描述

PUT example.com/api/users/{username}/reports/{report_id}/photos/{photo_id}

问题

  1. 在 URL 中添加资源 ID(即资源/ID)是一种好习惯,还是应该将其添加为查询参数?
  2. 这种链接资源的方法,即资源/id/sub-resource/id/等,是否可以接受且良好,还是应该将我的所有资源放在顶层并使用查询参数指定其位置?

推荐答案

恕我直言,你建模得很好.

IMHO you are modelling it well.

关于 1 我宁愿使用 resource/id 而不是查询参数.但是建模时必须记住的一件事是代理缓存机制等.所以不要忘记标题.

Regarding 1 I'd rather go with resource/id rather than query param. But one thing you must have in mind when modelling is the cache mechanism by proxy and so on. So do not forget the headers.

我去寻找用于过滤和那些排序的查询参数.

I go for query params for filtering and those sorts.

关于登录,凭据应在标题中,不需要特定资源.只需应用每个资源安全性.

About the login, the credentials should be in the headers, and no specific resource is needed. Just apply per resource security.

这篇关于分层 RESTful URL 设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆