简体   繁体   中英

Mapping Actions to Rest URI

I have a resource 'Customer' for which I have REST endpoints defined as,

| 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

  • Fetch top 5 customers by the amount paid
  • Fetch the last 3 customers
  • etc

How do I design URIs for actions like above?

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-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

/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.

what if I want to parameterize these actions like fetch-top-n customers

The general answer to parameters is to design your identifiers so that they align well with URI templates .

The most familiar variation is to use key value pairs on the query part, primarily because HTML forms support that spelling convention. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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