简体   繁体   English

将操作映射到 Rest URI

[英]Mapping Actions to Rest URI

I have a resource 'Customer' for which I have REST endpoints defined as,我有一个资源“客户”,我将 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             |

Now, I also have to design for some non CRUD operations like现在,我还必须设计一些非 CRUD 操作,例如

  • Fetch top 5 customers by the amount paid按支付金额获取前 5 名客户
  • Fetch the last 3 customers获取最后 3 个客户
  • etc等等

How do I design URIs for actions like above?如何为上述操作设计 URI?

My take on it has been to introduce a new controller with a separate endpoints for each function like:我的看法是引入一个新控制器,每个功能都有一个单独的端点,例如:

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

I am still not feeling confident about the above approach.我仍然对上述方法没有信心。 Also, what if I want to parameterize these actions like fetch-top-n customers另外,如果我想参数化这些操作,例如 fetch-top-n 客户怎么办

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

Those are both "fine", subject to the constraint that your implementation can tell that those terminal path segments aren't customer-ids.这些都“很好”,受限制,即您的实现可以告诉那些终端路径段不是客户 ID。

what if I want to parameterize these actions like fetch-top-n customers如果我想参数化这些操作,比如 fetch-top-n 客户怎么办

The general answer to parameters is to design your identifiers so that they align well with URI templates .参数的一般答案是设计您的标识符,以便它们与URI 模板很好地对齐。

The most familiar variation is to use key value pairs on the query part, primarily because HTML forms support that spelling convention.最熟悉的变体是在查询部分使用键值对,主要是因为 HTML 表单支持该拼写约定。 So your identifiers could be所以你的标识符可能是

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

But that's not required - you can encode the information into the path instead但这不是必需的 - 您可以将信息编码到路径中

/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

Those are all "fine".这些都是“好”的。 Use the spelling that works best for the people that you care about.使用最适合您关心的人的拼写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM