Skip to content

Commit

Permalink
Use custom validator for OpenAPI request body (apache#30596)
Browse files Browse the repository at this point in the history
* Use custom validator for OpenAPI request body

The default error message for an empty request body from Connexion
is quite unhelpful (taken directly from JSONSchema). This custom
validator emits a more helpful message for this particular context.

* Add test for custom request body validator

Co-Authored-By: maahir22 <[email protected]>

---------

Co-authored-by: maahir22 <[email protected]>
  • Loading branch information
uranusjr and maahir22 authored Apr 12, 2023
1 parent c2679c5 commit e89a7ee
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
17 changes: 17 additions & 0 deletions airflow/www/extensions/init_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
from os import path

from connexion import FlaskApi, ProblemException, Resolver
from connexion.decorators.validation import RequestBodyValidator
from connexion.exceptions import BadRequestProblem
from flask import Flask, request

from airflow.api_connexion.exceptions import common_error_handler
Expand Down Expand Up @@ -209,6 +211,20 @@ def resolve(self, operation):
return _LazyResolution(self.resolve_function_from_operation_id, operation_id)


class _CustomErrorRequestBodyValidator(RequestBodyValidator):
"""Custom request body validator that overrides error messages.
By default, Connextion emits a very generic *None is not of type 'object'*
error when receiving an empty request body (with the view specifying the
body as non-nullable). We overrides it to provide a more useful message.
"""

def validate_schema(self, data, url):
if not self.is_null_value_valid and data is None:
raise BadRequestProblem(detail="Request body must not be empty")
return super().validate_schema(data, url)


def init_api_connexion(app: Flask) -> None:
"""Initialize Stable API"""
base_path = "/api/v1"
Expand Down Expand Up @@ -245,6 +261,7 @@ def _handle_method_not_allowed(ex):
},
strict_validation=True,
validate_responses=True,
validator_map={"body": _CustomErrorRequestBodyValidator},
).blueprint
api_bp.after_request(set_cors_headers_on_response)

Expand Down
8 changes: 8 additions & 0 deletions tests/api_connexion/endpoints/test_task_instance_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,14 @@ def test_should_raise_403_forbidden(self):
)
assert response.status_code == 403

def test_should_raise_400_for_no_json(self):
response = self.client.post(
"/api/v1/dags/~/dagRuns/~/taskInstances/list",
environ_overrides={"REMOTE_USER": "test"},
)
assert response.status_code == 400
assert response.json["detail"] == "Request body must not be empty"

@pytest.mark.parametrize(
"payload, expected",
[
Expand Down

0 comments on commit e89a7ee

Please sign in to comment.