sanic-org / sanic

Accelerate your web app development | Build fast. Run fast.
https://sanic.dev
MIT License
18.05k stars 1.55k forks source link

Add optional content-type check in request.json property #2798

Open Bu3a3a opened 1 year ago

Bu3a3a commented 1 year ago

Is there an existing issue for this?

Is your feature request related to a problem? Please describe.

As far as I know request.json returns JSON body regardless of request's content-type. But sometimes it's useful (for consistency at least) to check content-type header before trying to parse request data, because parsing JSON data from (for example) 'application/x-www-form-urlencoded' seems strange and confusing.

Describe the solution you'd like

I'd like to see a Sanic config parameter that may be set in environment variable that enables strict content-type checking inside request methods and properties (disabled by default probably).

So that when someone tries to get request.json from application/x-www-form-urlencoded request, it throws an exception (and vice-versa - throws an exception if someone tries to get form data from application/json request.

Additional context

No response

Tronic commented 1 year ago

A middleware attached to an API handling JSON and possibly other input formats like that would be useful, but also not something that belongs to Sanic core. You mention parsing forms, and clearly the requirements vary largely by application. The good news is that you can easily write that yourself as a request middleware (to apply to your whole api) or as a decorator (if only some endpoints need strict JSON checking).