I've got a resource as follows where state is a enum:

{
  id: 123,
  industry: {
    id: 245,
    name: "Farming"
  },
  "scheduleDate": "2018-01-01",
  "state": "Requested|Approved|Standardized|Canceled|Done"
}

The only properties that can change are scheduledDate and state and I'm not sure what's the correct way to do this in my situation.

It would appropriate to use PATCH method to let update just those fields and I would do that, however I want to have just certain groups authorized to do these actions, it could be that person is authorized just to change stats to Standardized and I am not sure if PATCH works in my case.

What could be alternative ways to do this? I thought of going this way:

  • /api/v1/resource/123/reschedule
  • /api/v1/resource/123/approve
  • /api/v1/resource/123/standardize
  • /api/v1/resource/123/cancel

This doesn't seem too bad but isn't 100% REST either.

I'm using ASP.NET Core together with Identity Server to implement this.

So the real question is. If I were to use PUT, would it be possible to restrict certain users from updating this field? I couldn't find if this was possible.

有帮助吗?

解决方案

I do not see real problem with POST/PUT/PATCH: This is too theoretical without seeing the case in context. The API should serve use cases well - this is the starting point, which guides the choice of resources, URLs, addresses. In other words, API is for developers.

Personally I like POST here. From the "REST API Design Cookbook" by Mark Masse: "Rule: POST must be used to execute controllers" with an example:

POST /alerts/245743/resend

"This is the second use of POST in the design of REST APIs."

That is, HTTP verbs are fine for purely CRUD operations, but your API need not be confined to that. It's better to use operations from domain. And I believe this is what your example in the question is about.

And, yes, if you want all the way to https://en.wikipedia.org/wiki/HATEOAS - then it's also good to provide available operations a client can follow.

其他提示

Arguments over whether something is 100% or not can prevent you from getting something done and improving over time. Both approaches will work. You can do things in a more RPC way (with your separate endpoints for the type of action), and that would be an arguably correct thing to do. You can update your entry with a PUT or a PATCH and that would also be an arguably correct thing to do.

The trade-off isn't really all that serious either:

  • RPC: easy to understand and easy to implement
  • REST with PATCH: a little harder to understand, but not much
  • REST with PUT: full replacement could be called for here particularly since it's only 2 fields that get updated.

Just do what you feel is going to be the best. None of your alternatives are bad.

许可以下: CC-BY-SA归因
scroll top