sanic-org / sanic

Accelerate your web app development | Build fast. Run fast.

Home Page:https://sanic.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add optional content-type check in request.json property

Bu3a3a opened this issue · comments

Is there an existing issue for this?

  • I have searched the existing issues

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

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).