bottlepy / bottle

bottle.py is a fast and simple micro-framework for python web-applications.
http://bottlepy.org/
MIT License
8.44k stars 1.47k forks source link

A JSON body of "null" is valid JSON, but `Request.json` can't be used to disambiguate it from an empty/missing payload #1160

Closed sirosen closed 5 years ago

sirosen commented 5 years ago

I don't know if this impacts any real users, but as I'm working on a library with a bottle integration, I realized that there's an ambiguous case which Bottle is currently handling incorrectly.

Sending a request with an empty body, "", should not be considered valid JSON. However, sending a request with a body containing the string "null" is valid JSON, and when parsed produces None in python.

I would prefer that the framework raise a JSONDecodeError when you try to load Request.json on an empty request body.

Users may find this "technically incorrect" behavior convenient, but more likely they either rely on the built-in error handling already to capture invalid payloads, or they explicitly have their own handlers for decoding errors.

defnull commented 5 years ago

It may be technically correct that an empty string is no valid JSON, but I think sending an empty request to REST APIs is common enough to justify the current behavior. For example, when the request body is optional, you usually do not expect the client to send {} or none explicitly.

As always with bottle, if you need more control over some aspect (e.g. custom json datatypes), just look at the code for inspiration and write your own function. Request.json is just 10 lines long and easy to replace with custom code.