Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom action in RESTful service

I've been reading articles about RESTful services for a while, and I understand the importance of using VERBS against RESOURCES.

But there's one thing I fail to understand. What happens if we need to invoke a certain action that is not part of CRUD?

For example, consider I want to make a cat jump. Which format should we use?

Is the following RESTful?

http://host/cats/123/jump 
like image 731
SiN Avatar asked Apr 23 '12 11:04

SiN


People also ask

What is the use of custom actions?

Custom actions are used to provide a single prescriptive solution that might have more capability but usually gives the administrator less flexibility. Functions are a modular style of custom actions, simplifying the developer's code and reducing the learning curve.

What is an action in REST API?

Actions are basically RPC-like messages to a resource to perform a certain operation. The “actions” sub-collection can be seen as a command queue to which new action can be POSTed, that are then executed by the API.

What are REST actions?

REST verbs specify an action to be performed on a specific resource or a collection of resources. When a request is made by the client, it should send this information in the HTTP request: REST verb.


1 Answers

If cats/123 represents a resource then think about it this way: that resource can have many states (eating, walking, sleeping, jumping, pissing, ...). When you are designing an API using the REST architectural style, you want to permit a client application to make allowable requests to the resource that will change its state.

In the context of cats/123, you could do this through a series of POST requests that will cause the state of the resource to change. Taking advantage of the hypermedia capability in REST you could create a process like the requests and responses shown below. Notice that the allowable links change as a response to the POST. Also, the client application would be coding to the properties contained in the Links array and not the actual URI's contained in the Href properties.

Request:

GET cats/123 

Response:

{     "Color" : "black",     "Age"   : "2",     "Links":[     {         "Food":"kibbles",         "Method":"POST",         "Href":"http://cats/123",         "Title":"Feed the cat"     },     {         "Scare":"yell real loud",         "Method":"POST",         "Href":"http://cats/123",         "Title":"Scare the cat"     }] } 

Request:

POST cats/123  {     "Food":"kibbles" } 

Response:

{     "Color" : "black",     "Age"   : "2",     "Tummy" : "full"     "Links":[     {         "Sleep":"lap",         "Method":"POST",         "Href":"http://cats/123",         "Title":"Pet the cat"     },     {         "Scare":"yell real loud",         "Method":"POST",         "Href":"http://cats/123",         "Title":"Scare the cat"     }] } 
like image 71
Sixto Saez Avatar answered Oct 14 '22 06:10

Sixto Saez