【问题标题】:Mapping Actions to Rest URI将操作映射到 Rest URI
【发布时间】:2021-12-01 19:30:03
【问题描述】:

我有一个资源“客户”,我将 REST 端点定义为,

| URI                            | Function                            |
| ------------------------------ | ----------------------------------  |
| /apiv1/customers/              | {GET} Fetch all customers           |
| /apiv1/customers/{customer-id} | {GET} Fetch details of the customer |
| /apiv1/customers/              | {POST} Add a new customer           |
| /apiv1/customers/{customer-id} | {PUT} Update a customer             |

现在,我还要设计一些非 CRUD 操作,比如

  • 按支付金额获取前 5 位客户
  • 获取最后 3 位客户

如何为上述操作设计 URI?

我的看法是引入一个新的控制器,每个函数都有一个单独的端点,例如:

  • /apiv1/customers/fetch-top-5
  • /apiv1/customers/fetch-last-3

我仍然对上述方法没有信心。另外,如果我想参数化这些操作,比如 fetch-top-n 客户,该怎么办

【问题讨论】:

    标签: java rest uri rpc


    【解决方案1】:
    /apiv1/customers/fetch-top-5
    /apiv1/customers/fetch-last-3
    

    这些都“很好”,受制于您的实现可以告诉这些终端路径段不是客户 ID 的约束。

    如果我想参数化这些操作,比如 fetch-top-n 个客户,该怎么办

    参数的一般答案是设计您的标识符,以便它们与URI templates 很好地对齐。

    最熟悉的变体是在查询部分使用键值对,主要是因为 HTML 表单支持该拼写约定。所以你的标识符可能是

    /apiv1/customers?fetch-top=5
    /apiv1/customers?fetch-last=3
    

    但这不是必需的 - 您可以将信息编码到路径中

    /apiv1/customers?fetch-top=5
    /apiv1/customers/fetch-top=5
    /apiv1/customers/fetch-top/5
    /apiv1/customers/fetch/top=5
    /apiv1/customers/fetch/top/5
    

    这些都“很好”。使用最适合您关心的人的拼写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2016-01-31
      相关资源
      最近更新 更多