Thursday, June 16, 2011

GET or POST method

A very old topic. But always remember the guiding rules:

1. No matter how many times a http request is submitted anew, if the http request will not result in a state-changing action, use GET.
For example, searching repeatedly will not change the database's contents(Well, you may want to record the statistic of keywords being searched which may cause change in database, but when i say the db's content won't get changed, you know what i mean: the request should not have detrimental effect if submitted repeatedly), so the search form could be a good candidate for GET method.

2. If a http request will cause state-changing action, use POST. For instance, charging a credit card.

Now let's explain why these rules. First of all, we have to know the distinction between GET and POST.

The first and very obvious difference is using GET, the data is submitted via the URL. And you may also know that the maximum URL length depends on the browser.

Another distinction is if a request had been submitted using POST method, and the user tries to reload the page, the browser will warn the user if he wants to submit the data again so it can prevent the request from being executed again accidently.

Now, let's assume we just submit our credit card data and get charged. If the method is GET, and we accidently reload the page, the browser will not warn us anything and we may get charged twice. So we better use POST in this case.

Anyway, they are just guiding rules. It doesn't mean you have to follow every time. Come to the end, it all depends on the requirements. For example, if you are developing a bunch of APIs and decide that all requests must be submitted using POST method, then just do it.

No comments: