如何正确创建自定义 REST API 端点

How to create custom REST API endpoint correctly

假设我们有客户:/api/customers (/api/customers/{id})

内容如下:

[{
    name: "Mike",
    age: 20,
    amount: 300
},
{
    name: "John",
    age: 30,
    amount: 600
}]

但是当您必须执行各种数据操作时,会有不同的任务。

假设我们需要显示花费最多的客户(在 "amount" 字段中)。

此请求的端点应该是什么样的?

我有一些建议如何做到这一点,请指正:

1. /api/customers/spent-more

2. /api/customers-spent-more

3. /api/customers?action=spent-more

你是如何完成类似任务的,分享经验

提供排序和限制作为参数

/api/customers?sort_by=amount&limit=1&order=desc

回答是消费最多的一位顾客。当然,该方法也可用于其他用例。

正确的端点是:

  1. /api/customers/spent-more

然后您可以将任何其他查询参数作为请求字符串的一部分传递。

理论上,您可以使用:

  1. /api/customers?action=spent-more

并在后端有一个开关,returns 所需的数据取决于发送的操作,但每种方法的优缺点取决于您的体系结构以及您最终将执行多少操作.我会说传统的 MVC 架构将决定前者。