10

When to use RequestHandler.get_argument(), RequestHandler.get_query_argument() and RequestHandler.get_body_argument()?

What is the use-case for each of them?

Also what does the request.body and request.argument do in these cases? Which are to be used in which scenarios?

And, is there a request.query or something similar too?

Anirban Roy Das
  • 262
  • 4
  • 14

1 Answers1

19

Most HTTP requests store extra parameters (say, form values) in one of two places: the URL (in the form of a ?foo=bar&spam=eggs query string), or in the request body (when using a POST request and either the application/x-www-form-urlencoded or multipart/form-data mime type).

The Request.get_query_argument() looks for URL parameters, the RequestHandler.get_body_argument() lets you retrieve parameters set in the POST body. The RequestHandler.get_argument() method retrieves either a body or a URL parameter (in that order).

You use Request.get_argument() when you explicitly don't care where the parameter comes from and your endpoint supports both GET and POST parameters. Otherwise, use one of the other methods, to keep it explicit where your parameters come from.

The Request.get_*_argument methods use the request.body_arguments and request.query_arguments values (with request.arguments being their aggregate), decoded to Unicode. request.body is the undecoded, unparsed raw request body; and yes, there is an equivalent self.query containing the query string from the URL.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @martin-pieters Thanks Martin. What about the second part? what is the difference between request.body and request.argument? and is there any request.query? – Anirban Roy Das Jan 15 '16 at 23:19
  • @AnirbanRoyDas: sorry, missed that, added now. – Martijn Pieters Jan 15 '16 at 23:26
  • Finally got it. I have added another question, if you find time then please have a look http://stackoverflow.com/questions/34821740/http-setting-content-type-of-request-or-response-header-to-application-json – Anirban Roy Das Jan 15 '16 at 23:44
  • This answer should just be copied to the documentation! Very helpful, thanks. – Miguel Feb 05 '17 at 18:26
  • Does tornado parse JSON format body with `get_body_argument()`? and what's the difference with `get_*_argument()` and `get_*_arguments()`? – Mengo May 03 '17 at 21:41
  • 1
    @JasonXie there is no JSON support, no. Query and POST parameters can appear multiple times (`foo=42&foo=81`); `get_*_arguments()` returns a list with all values for a given parameter, `get_*_argument()` returns just the last value if there are is more than one. – Martijn Pieters May 03 '17 at 22:48
  • 1
    Wow, that was not obvious at all from the docs I was reading, so thanks for this. If only query arguments had a less generic name. – Domino Sep 12 '17 at 21:38