简体   繁体   中英

Should an API ever expose actions like “Approve” or “Deny”?

I'm building my first API and I'm wondering if - since these actions are central to the application and will be leveraged by any client - I should build my api in a way that exposes actions outside of the typical CRUD scenarios. I have stuff laid down for Reports, but I need to allow users to approve or deny reports too, so I'm thinking something like this:

/api/report/id/approve
/api/report/id/deny

would be useful. Does this violate any standards or practices when it comes to APIs?

There is nothing wrong with exposing those URLs. REST does not mandate anything about URLs, it's a set of constraints that don't have anything to do with that. One of them is HATEOS. If you expose those links somehow to change the state of report as part of the resource representation of a report, you would be using that constraints as part of your implementation. For example,

<report>
  <id>2</id>
  <link url="api/report/2/approve" rel="approve"/>
  <link url="api/report/2/deny" rel="deny"/>
</report>

That will make your API more discoverable, and it is how the web works today. Another constraint is that you need to use the HTTP verbs in the right way. An HTTP GET to that link would not be valid as it would change the state of the resource. An HTTP GET should be safe, so it should not alter the state of the resource. An HTTP POST would be more suitable for that scenario. Those are some examples of how you can apply the different constraints to your web api, but remember, there is nothing wrong with that design.

Regards, Pablo.

I think how you structure your API is entirely up to you. Although it probably couldn't be called 'RESTful' and is more akin to RPC, does it really matter so long as you are providing your API users with the functionality they need?

There are several different ways to achieve what you require and many opinions and 'best practices' you can consider but ultimately as long as the API achieves it's aims it doesn't matter how you implement it.

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