Here is my demo url: https://github.com/jiamo/flask_demo
normal
python run.py
http 127.0.0.1:5000/api/test testlist=='[1]' # ok
curl "127.0.0.1:5000/api/test?testlist=%5B1%5d" # ok
failed:
python -m tests.test_apis
Traceback (most recent call last):
File "demo/__init__.py", line 16, in get
args_parser = self.get_parser.parse_args()
File "/usr/lib/python2.7/site-packages/flask_restful/reqparse.py", line 301, in parse_args
value, found = arg.parse(req, self.bundle_errors)
File "/usr/lib/python2.7/site-packages/flask_restful/reqparse.py", line 161, in parse
source = self.source(request)
File "/usr/lib/python2.7/site-packages/flask_restful/reqparse.py", line 102, in source
value = getattr(request, l, None)
File "/usr/lib/python2.7/site-packages/werkzeug/local.py", line 343, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/python2.7/site-packages/flask/wrappers.py", line 108, in json
return self.get_json()
File "/usr/lib/python2.7/site-packages/flask/wrappers.py", line 145, in get_json
rv = self.on_json_loading_failed(e)
File "/usr/lib/python2.7/site-packages/flask/wrappers.py", line 162, in on_json_loading_failed
raise BadRequest()
BadRequest: 400: Bad Request\n', u'res'
But without using RequestParser() the test is ok like my code test_demo2
I think I found the reason. The problem is that I using 'Content-Type': 'application/json' in GET method.
In source your code
values = MultiDict()
for l in self.location:
value = getattr(request, l, None)
if callable(value):
value = value()
if value is not None:
values.update(value)
return values
May be we need a try catch to continue find the another possible location.
Actually, as per RFC 2616 (HTTP/1.1), "The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient". Therefore it should not be set if the body of the request is empty, which seems to be the case in your test code.
So if your requests states that a JSON-body is included, and the parser can not parse the body as valid JSON (because it is void), a response with error code 400 "Bad Request" is actually perfectly in line with the HTTP standard. As a rule of thumb: only set the Content-Type header if your method is POST or PUT.
Thanks for your explain.
Why doesn't reqparse return any meaningful error messages? Just came across this case in a more complex setup and tracing it down was a pain.
Most helpful comment
Why doesn't reqparse return any meaningful error messages? Just came across this case in a more complex setup and tracing it down was a pain.