HTTP method to represent "fire and forget" actions in RESTful service - http

Thinking about REST, it's relatively easy to map HTTP methods to CRUD actions: POST for create, GET for read, etc. But what about "fire and forget" actions? What HTTP method would best represent a fire and forget action such as triggering a batch job (in which no response is sent back to the caller)?
POST would spring to mind, but I think GET is also an appropriate method because 99% of the time you only supply a bunch of parameters to these types of actions. What do you think?

POST would spring to mind, but I think GET is a more appropriate method because 99% of the time you only supply a bunch of parameters to these types of actions. What do you think?
External State
I think that the number of parameters you use has nothing to do with the verb you use. The key issue is are you changing externally visible state?
BatchJob Resources
In your example, if the batch job does not affect the externally visible state of any object then you could implement it as a batch job. However you could model your batch job as a resource with an associated resource container.
You could use a Post to create a new BatchJob resource and allow the user to do a GET to see the progress of the job so far. You could do a GET on the resource container to list all of the running batch jobs, possibly calling DELETE to kill one.

You should use POST if your request modifies data, and GET if it only reads it.
Since your request is "fire and forget", I guess that it's modifying data, so use POST.

I think in the general case we might well supply various payload parameters, and these plausibly might exceed what's possible with GET, so POST is quite reasonable - the action of starting a job doesn't to me fit well with GET sematics.
One thought, might not the action actually return a response:
a). No, sir, that's an impossible request we can't start your job.
b). Understood, your job reference is 93.

If you're concerned at that level, perhaps HEAD is the HTTP method you want; it's identical to GET, with the stipulation that the response body is empty. That sounds to me spot-on to what you're asking for?

I'm bringing this question back from the dead to offer a different point of view.
Now that CORS is prevalent, the choice between using GET or POST becomes a matter of if you want anyone who knows your API URI to be able to trigger the batch job (GET), or if you want to restrict the origin of the request to prevent any Joe with a computer from triggering the job (POST).

Related

how GET method is idempotent

How GET method is idempotent and POST is not. we are using it in form submission, if we submitting it twice it will re-submitting the form data's. And why we are not using GET for order placing or purchasing products for instance when it is idempotent.
An idempotent HTTP method is a HTTP method that can be called many times without different outcomes. It would not matter if the method is called only once, or ten times over. The result should be the same. Again, this only applies to the result, not the resource itself.
a=10; //This is idempotent: no matter how many times we execute this statement, a will always be 4.
a++; //This is not idempotent. Executing this 10 times will result in a different outcome as when running 5 times.
Now, coming to your query.
If we use GET method for order placing/purchasing products, the order will be placed no matter the product is gone out of stock. In contrast if you use the to POST method the result will be different for each new request made for purchasing product.
Below example is not idempotent because for every new request the outcome will be different
https://accounts.google.com/Login#identifier
The GET method should be used to send the information from the browser to the server in the URL. Below is an example usage of GET method.
http://www.google.co.in/search?q=cristiano+ronaldo
Below is the answer to your query in the comments:
When users revisit a page that resulted from a form submission, they might be presented with the page from their history stack (which they had probably intended), or they might be told that the page has now expired. Typical user response to the latter is to hit Reload.
This is harmless if the request is idempotent, which the form author signals to the browser by specifying the GET method.
Browsers typically will (indeed "should") caution their users if they are about to resubmit a POST request, in the belief that this is going to cause a further "permanent change in the state of the universe", e.g. ordering another Mercedes-Benz against their credit card or whatever. If users get so accustomed to this happening when they try to reload a harmless idempotent request, then sooner or later it's going to bite them when they casually [OK] the request.
Now, while implementing those two methods GET and POST, a developer should consider the security issues and write the code in the particular method. Any code can be written in both the methods considering all the limits of GET method(size of url etc.), But this is not a good practice.
GET -> for information retrieval.(If you want to read data without changing state)
POST -> for information creation/updation/deletion.

Is it ok to model a computation as a web resource (REST resource)?

Let's say I have a component wich performs an addition as a business operation.
I don't need the result of the sum to be persisted anywhere because, let's say, the only thing that matters is the result of the addition.
Let´s say that the client component should get interested in saving the result of the addition, so I need to indicate the client how to save the result of the addition, so he can come back later and retrieve this result.
May the addition service be modeled as a web resource? Something like:
GET api.mycompany.com/addition?param1=x&param2=y
should return the result of the business operation. The response may present the following as a link (here comes the hypermedia) to persist the result:
POST api.mycompany.com/addition?param1=x&param2=y
Is this approach correct? -In the sense of a truly restful api -
Considering CRUD operations, this one:
GET api.mycompany.com/addition?param1=x&param2=y
Is idempotent, safe and cacheable, so I'll consider it as a RESTful GET.
As soon as your parameters become more complex, you could POST them to your 'addition' resource, returning a URL to computed result.
Yes, it is fine. But perhaps it is better to have a resource called operation that returns a list of links to supported operations. You could then have operation/addition?param1=x&param2=y and so on and so fort. Of course, the links should be opaque and the documented media-type returned by a call to the operation resource should provide information about the other available resources.

How to create a RESTful object with server calculated fields

I have an object:
Account
{
Id,
Name,
CurrentBalance
}
Id is an immutable key, Name is a mutable string, and CurrentBalance is calculated from all of the transactions associated with the account.
I am stuck on the fact that GET \Accounts\{Id} will not be idempotent because changes to a transaction will cause a change in CurrentBalance. Should I remove this field from the object and make a request like
POST \Accounts\{Id}\CurrentBalance
But now I have to make multiple calls to the server to get the CurrentBalance of all objects:
GET \Accounts
POST \Accounts\{Id1}\CurrentBalance
POST \Accounts\{Id2}\CurrentBalance
POST \Accounts\{Id3}\CurrentBalance
....
I guess I am just looking to see if there is already a standard way to handle this that I am missing?
UPDATE
Part 2 if the original object is ok via GET. My only way to update the Account.Name is via a PATCH as I cannot allow an update to CurrentBalance, correct?
NOTE
I realize I could put this on the client to have to get all transactions and calculate it, but I would prefer to do this on the server for multiple reasons
Idempotency does not mean that you must always get the same response back.
Consider the resource /TodaysWeather. It would be pretty useless if it always returned the same value.
Idempotency simply states that if a client makes the same request multiple times instead of just once, the impact on the system (from the client's perspective) will be the same.
I just re-read the HTTP specs and realized that if I want to be truly RESTful I have to make multiple calls because GET has to be safe.
In particular, the convention has been established that the GET and
HEAD methods SHOULD NOT have the significance of taking an action
other than retrieval.
I am not deleting this question because I think it could help others in the future, but if the majority disagree I will delete it
If it's important that you're able to PUT some data, then immediately retrieve the same data via GET, then you could simply treat it as a different resource entirely, e.g.:
# Change an account name
PUT \Accounts\{id}
# Get accounts/names/balances
GET \AccountDetails
# Get balance of an account
GET \AccountDetails\{id}\CurrentBalance
However, there's really no good reason to go through the trouble of doing that. Your PUT is idempotent as long as making the same request multiple times doesn't change the state of the system. Not changing the system's state if some spurious value is submitted is the correct behavior. In fact, if someone does try a PUT including CurrentBalance, you might want to return a 400 (Bad Request) status explaining that CurrentBalance can't be updated.

How should Transient Resources be retrieved in a RESTful API

For a while I was (wrongly) thinking that a RESTful API just exposed CRUD operation to persisted entities for a web application. When you code something up in "the real world" you soon find out that this is not enough. For example, a bank account transfer doesn't have to be a persisted entity. It could be a transient resource where you POST to /transfers/ and in the payload you specify the details:
{"accountToCredit":1234, "accountToDebit":5678, "amount":10}
Using POST here makes sense because it changes the state on the server ($10 moves from one account to another every time this POST occurs).
What should happen in the case where it doesn't affect the server? The simple first answer would be to use GET. For example, you want to get a list of savings and checking accounts that have less than $100. You would then call something like GET to /accounts/searchResults?minBalance=0&maxBalance=100. What happens though if your search parameter need to use complex objects that wouldn't fit in the maximum length of a GET request.
My first thought was to use POST, but after thinking about it some more it should probably be a PUT since it isn't changing the state of the server, but from my (limited) understanding I always though of PUT as updating a resource and POST as creating a resource (like creating this search results). So which should be used in this case?
I found the following links which provide some information but it wasn't clear to me what should be used in the different cases:
Transient REST Representations
How to design RESTful search/filtering?
RESTful URL design for search
I would agree with your approach, it seems reasonable to me to use GET when searching for resources, and as said in one of your provided links, the whole point of query strings is for doing things like search. I also agree that PUT fits better when you want to update some resource in an idempotent way (no matter how many times you hit the request, the result will be the same).
So generally, I would do it as you propose. Now, if you are limited by the maximum length of GET request, then you could use POST or PUT, passing your parameters in a JSON, in a URI like:
PUT /api/search
You could see this as a "search resource" where you send new parameters. I know it seems like a workaround and you may be worried that REST is about avoiding verbs in the URIs. Well, there are few cases that it's still acceptable and RESTful to use verbs, e.g. in cases where calculation or conversion is involved to generate the result (for more about this, check this reference).
PS. I think this workaround is still RESTful, but even if it wasn't, REST isn't an obsession and an ultimate goal. Being pragmatic and keeping a clean API design might be a better approach, even if in few cases you are not RESTful.

Why is the HTTP verb POST called POST?

The other verbs all make sense to me, but I don't have much context for "post" as a verb. Is it like post as in Post Office (which makes some sense, although seems like a stretch) or post like post on a bulletin board (makes less sense to me)? Does anyone know who decided on "POST" and why it was selected?
Well, "post like post on a bulletin board" comes pretty close to the answer, I guess. In the end, that's exactly one of those functionalities this method was designed for. POST is always meant to post stuff to some kind of 'factory' to be handled by it - otherwise you could just use PUT. Let's have a look at RFC2616, Section 9.5:
The POST method is used to request that the origin server accept
the entity enclosed in the request as a new subordinate of the
resource identified by the Request-URI in the Request-Line. POST is
designed to allow a uniform method to cover the following
functions:
- Annotation of existing resources;
- Posting a message to a bulletin board, newsgroup, mailing list,
or similar group of articles;
- Providing a block of data, such as the result of submitting a
form, to a data-handling process;
- Extending a database through an append operation.
Of course this is not the exact definition of why it is called POST, but I think this might give some clues about the idea behind it.
Maybe we could also have a look at some meanings of the word 'post' (http://www.thefreedictionary.com/Post, the 3rd definition) - according to that, post as a verb can mean
To mail (a letter or package)
To inform of the latest news
To transfer (an item) to a ledger in bookkeeping
To make the necessary entries in (a ledger)
And this is exactly what POST does (metaphorically). If you want to send en email, you let your email-provider handle it and then inform you about the state. And this is also the difference between PUT and POST: If the client is in charge of handling the resource, you use PUT (because you know what to put and where to put it).
So, theoretically, if you knew the IP-address of the person you want to send the email to, you wouldn't need your provider to find this stuff out for you. But now, you know what to put, but not exactly where. So in this case, you use POST. You 'inform the server of the latest news' and the server decides where to put it. So you can think of it as 'transfering an item' to a resource that's already present (like a thread in a forum or something) - you just want to append something.
I hope this makes any sense...
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:
Annotation of existing resources;
Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
Providing a block of data, such as the result of submitting a form, to a data-handling process;
Extending a database through an append operation.
W3 / POST
REST asks developers to use HTTP methods explicitly and in a way that's consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping:
To create a resource on the server, use POST.
To retrieve a resource, use GET.
To change the state of a resource or to update it, use PUT.
To remove or delete a resource, use DELETE.
IBM / REST
When we are POSTing, we really are sending new data (creating resource) but not going to get it or calling about updates or asking for shredding our older documnets.
I don't think that post as in 'to post a letter' is much of a stretch. A POST request is a message containing data after all. As to the who, the verbs come from HTTP, so the origins would be the Html spec written by Tim Berners-Lee in 1995.

Resources