Question

I wonder, what would the more RESTFul, flexible and better approach of updating(!) a field (state) of an item

/api/v1/items/:id?action=start 
/api/v1/items/:id/start 
/api/v1/items/:id/ + action in the body
/api/v1/items/:id/status/{active|stopped}

or items

/api/v1/items?action=start 
/api/v1/items/start 
/api/v1/items/ + action in the body
/api/v1/items/status/{active|stopped}  
Was it helpful?

Solution

I would prefer the third API structure:

/api/v1/items/:id/ + action in the body

My reasons include:

  • According to the Richardson Maturity Model the URL should point to a specific resource or set of resources. You do not want to add update information within the URL, as it doesn't qualify as a valid endpoint.
  • You want to use PUT for update/replacement operations which affect a resource. Let the URL select the resource and let the body define the exact fields you want to update, and any other logic otherwise.
  • Using the body rather than the query string allows you to insert arbitrarily large information (to a certain limit, but greater than a query string) which logically might be paired with the operation (start in your case). It allows greater flexibility in extending the operation in the future as well.
  • You can probably list the relevant actions that can be performed on the endpoint inside the response of /api/v1/items. This would be a list of informative hypermedia controls. Again, the Richardson maturity model provides a very good example.

OTHER TIPS

As alternative you can implement the PATCH method. It would provide you with the possibility to update selective fields. The only problem with PATCH is thats its unknown because the RFC is young. The actual implemention depends on your server and client side libraries and frameworks.

When you dont want to use PATCH the only alternative is to implement overriden POST and define the update mechanism. For example, you can say: Every field != null will override the resource field value.

Lets re phrase the question: how do i change few attribute of my resource. (status is just another attribute)

Answer:

identify a resource.

Use POST (since the request is non idempotent) supply in body, since in future you may need to change more attribute than just status for this resource.

POST /api/v1/items/:id + action in the body

use only POST method.

Reason: Put should be used when it changes the complete set of properties not one or partial property(ies).

Please, let’s move on. We don’t need to use PUT for every state change in HTTP. REST has never said that we should. It is okay to use POST - roy t fielding

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top