Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve JSON req error on disallowed empty body #1761

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Improve JSON req error on disallowed empty body
Currently, when a request body is empty, the JSON request validator
would parse it into None, which is later passed down to the JSON Schema
validator. However, jsonschema's validation error message for this case
(when nullable is false) "None is not of type 'object'" is not
particularly friendly to either the API user, nor the website developer.

This change adds a specific check before the None value is passed to
jsonschema to emit a better error message directly.

I also added some drive-by improvements on function argument typing
since _validate in validators don't seem to expect receiving None, but
_parse (the result of which is passed to _validate) is totally allowed
to return None (or anything really). This does not seem to reflect the
logic well.
  • Loading branch information
uranusjr committed Oct 29, 2023
commit e7a9c92797e67a8ee1f2c36c7180e2e757736618
9 changes: 5 additions & 4 deletions connexion/validators/form_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,13 @@ async def _parse(self, stream: t.AsyncGenerator[bytes, None], scope: Scope) -> d

return data

def _validate(self, data: dict) -> None:
def _validate(self, body: t.Any) -> t.Optional[dict]:
if not isinstance(body, dict):
raise BadRequestProblem("Parsed body must be a mapping")
if self._strict_validation:
self._validate_params_strictly(data)

self._validate_params_strictly(body)
try:
self._validator.validate(data)
self._validator.validate(body)
except ValidationError as exception:
error_path_msg = format_error_with_path(exception=exception)
logger.error(
Expand Down
4 changes: 3 additions & 1 deletion connexion/validators/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ async def _parse(
except json.decoder.JSONDecodeError as e:
raise BadRequestProblem(detail=str(e))

def _validate(self, body: dict) -> None:
def _validate(self, body: t.Any) -> t.Optional[dict]:
if not self._nullable and body is None:
raise BadRequestProblem("Request body must not be empty")
try:
return self._validator.validate(body)
except ValidationError as exception:
Expand Down
Loading