Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(api): split validated_request into request and response validators (#101144)

posthog[bot]574f665936bf
diff --git a/posthog/api/mixins.py b/posthog/api/mixins.py
index 7667e2a5311c..58a755d1e80d 100644
--- a/posthog/api/mixins.py
+++ b/posthog/api/mixins.py
@@ -1,3 +1,4 @@
+import copy
from collections.abc import Callable
from functools import wraps
from typing import Any, Generic, TypeVar, cast
@@ -13,12 +14,15 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.file_system.file_system_logging import log_api_file_system_view
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
logger = structlog.get_logger(__name__)
T = TypeVar("T", bound=BaseModel)
+_SCHEMA_HINT = "Please update the provided API schema to ensure API docs remain up to date"
+
class ValidatedRequest(Request):
"""
@@ -59,6 +63,160 @@ class PydanticModelMixin:
raise ParseError("JSON parse error - {}".format(str(exc)))
+@frozen
+class _RequestValidator:
+ """Validates the query params and the body of a request against the declared serializers."""
+
+ view_name: str
+ request_serializer: type[serializers.Serializer] | None
+ query_serializer: type[serializers.Serializer] | None
+ strict: bool
+ include_serializer_context: bool
+
+ def attach_validated_data(self, view: Any, request: Request) -> None:
+ validated = cast(ValidatedRequest, request)
+ validated.validated_query_data = {}
+ if self.query_serializer is None and self.request_serializer is None:
+ # Building the context reads `view.team`, which can hit the database, and no serializer wants it.
+ return
+
+ context = (
+ {"request": request, "view": view, "team": getattr(view, "team", None)}
+ if self.include_serializer_context
+ else {}
+ )
+
+ if self.query_serializer is not None:
+ query = self.query_serializer(data=request.query_params, context=context)
+ query.is_valid(raise_exception=True)
+ validated.validated_query_data = query.validated_data
+
+ if self.request_serializer is not None:
+ body = self.request_serializer(data=request.data, context=context)
+ if not body.is_valid(raise_exception=self.strict) and settings.DEBUG:
+ logger.warning(
+ f"Request body does not match declared serializer in @validated_request decorator. {_SCHEMA_HINT}",
+ view_func=self.view_name,
+ serializer_class=self.request_serializer.__name__,
+ validation_errors=body.errors,
+ )
+ validated.validated_data = body.validated_data
+
+
+@frozen
+class _ResponseValidator:
+ """Checks what a view returned against the responses the decorator declares."""
+
+ view_name: str
+ responses: dict[int, OpenApiResponse | None] | None
+ strict: bool
+
+ def check(self, view: Any, result: Any) -> None:
+ # Every check below either raises under strict mode or logs under DEBUG. Outside both it does nothing.
+ if not (self.strict or settings.DEBUG):
+ return
+
+ if not self.responses:
+ self._report(
+ "Responses parameter is required when strict_response_validation is True",
+ f"No responses parameter defined in @validated_request decorator. {_SCHEMA_HINT}",
+ )
+ return
+
+ if not isinstance(result, Response):
+ self._report(
+ f"View must return a Response object when using @validated_request with response serializers. Got {type(result).__name__}",
+ f"View must return a Response object when using @validated_request with response serializers. {_SCHEMA_HINT}",
+ result_type=type(result).__name__,
+ )
+ return
+
+ status_code = result.status_code
+ if status_code not in self.responses:
+ self._report(
+ f"Response status code {status_code} not declared in responses parameter of the @validated_request decorator. "
+ f"Declared status codes: {sorted(self.responses.keys())}",
+ f"Response status code not declared in responses parameter of the @validated_request decorator. {_SCHEMA_HINT}",
+ status_code=status_code,
+ declared_status_codes=sorted(self.responses.keys()),
+ )
+ return
+
+ response_config = self.responses[status_code]
+ response_serializer = response_config.response if response_config else None
+ if response_serializer is None:
+ self._check_declared_empty(status_code, result.data)
+ else:
+ self._check_body(view, status_code, result.data, response_serializer)
+
+ def _report(self, error: str, warning: str, **log_context: Any) -> None:
+ if self.strict:
+ raise serializers.ValidationError(error)
+ logger.warning(warning, view_func=self.view_name, **log_context)
+
+ def _check_declared_empty(self, status_code: int, data: Any) -> None:
+ if data in (None, {}, []):
+ return
+ self._report(
+ f"Response status code {status_code} is declared with no body, but response contains data",
+ f"Response status code {status_code} is declared with no body, but response contains data. {_SCHEMA_HINT}",
+ status_code=status_code,
+ )
+
+ def _check_body(self, view: Any, status_code: int, data: Any, response_serializer: Any) -> None:
+ # A PolymorphicProxySerializer only describes the schema; it cannot validate data.
+ # `many=True` wraps one in a plain ListSerializer, so the child needs the same check.
+ if isinstance(response_serializer, PolymorphicProxySerializer) or isinstance(
+ getattr(response_serializer, "child", None), PolymorphicProxySerializer
+ ):
+ return
+
+ context: dict[str, Any] = getattr(view, "get_serializer_context", lambda: {})()
+ serialized = self._instantiate(response_serializer, data, context)
+
+ try:
+ body_matches_serializer = serialized.is_valid(raise_exception=self.strict)
+ except Exception as exc:
+ # `is_valid` only handles DRF's ValidationError. A DataclassSerializer can raise other
+ # errors for a valid response, and this check is advisory under DEBUG, so warn instead.
+ if self.strict:
+ raise
+ logger.warning(
+ "Response serializer could not parse the response it declared for status code "
+ f"{status_code} in the responses parameter of the @validated_request decorator. "
+ "The response was returned unchanged; check the declared serializer.",
+ view_func=self.view_name,
+ status_code=status_code,
+ serializer_class=type(serialized).__name__,
+ error=str(exc),
+ )
+ return
+
+ if not body_matches_serializer:
+ logger.warning(
+ f"Response data does not match declared serializer for status code {status_code} declared in responses parameter of the @validated_request decorator. {_SCHEMA_HINT}",
+ view_func=self.view_name,
+ status_code=status_code,
+ serializer_class=type(serialized).__name__,
+ validation_errors=serialized.errors,
+ )
+
+ @staticmethod
+ def _instantiate(response_serializer: Any, data: Any, context: dict[str, Any]) -> serializers.BaseSerializer[Any]:
+ # drf-spectacular accepts a serializer class or an instance, so handle both.
+ if not isinstance(response_serializer, serializers.BaseSerializer):
+ return response_serializer(data=data, context=context)
+
+ # A declared instance can carry constructor arguments that rebuilding from its class drops,
+ # such as `allow_empty` on a `many=True` list or a keyword the serializer requires. DRF's
+ # deepcopy replays the original constructor call, including for the child of a
+ # ListSerializer, so copy the declared instance and bind only the response data to the copy.
+ serialized = copy.deepcopy(response_serializer)
+ serialized.initial_data = data
+ serialized._context = context
+ return serialized
+
+
def validated_request(
request_serializer: type[serializers.Serializer] | None = None,
*,
@@ -103,6 +261,17 @@ def validated_request(
if query_serializer is not None:
parameters.append(query_serializer)
+ request_validator = _RequestValidator(
+ view_name=view_func.__name__,
+ request_serializer=request_serializer,
+ query_serializer=query_serializer,
+ strict=strict_request_validation,
+ include_serializer_context=include_serializer_context,
+ )
+ response_validator = _ResponseValidator(
+ view_name=view_func.__name__, responses=responses, strict=strict_response_validation
+ )
+
@extend_schema(
request=request_serializer,
parameters=parameters if parameters else None,
@@ -115,162 +284,9 @@ def validated_request(
)
@wraps(view_func)
def wrapper(self, request: Request, *args, **kwargs) -> Response:
- validated_request = cast(ValidatedRequest, request)
- validated_request.validated_query_data = {}
-
- serializer_context = (
- {"request": request, "view": self, "team": getattr(self, "team", None)}
- if include_serializer_context
- else {}
- )
-
- if query_serializer is not None:
- query_serializer_instance = query_serializer(data=request.query_params, context=serializer_context)
- query_serializer_instance.is_valid(raise_exception=True)
- validated_request.validated_query_data = query_serializer_instance.validated_data
-
- if request_serializer is not None:
- serializer = request_serializer(data=request.data, context=serializer_context)
- req_validation_result = serializer.is_valid(raise_exception=strict_request_validation)
-
- if not req_validation_result and settings.DEBUG:
- logger.warning(
- "Request body does not match declared serializer in @validated_request decorator. Please update the provided API schema to ensure API docs remain up to date",
- view_func=view_func.__name__,
- serializer_class=request_serializer.__name__,
- validation_errors=serializer.errors,
- )
-
- validated_request.validated_data = serializer.validated_data
-
+ request_validator.attach_validated_data(self, request)
result = view_func(self, request, *args, **kwargs)
-
- # Step 1: Check if responses are defined at all
- if not responses:
- if strict_response_validation:
- raise serializers.ValidationError(
- "Responses parameter is required when strict_response_validation is True"
- )
- elif settings.DEBUG:
- logger.warning(
- "No responses parameter defined in @validated_request decorator. Please update the provided API schema to ensure API docs remain up to date",
- view_func=view_func.__name__,
- )
- return result
-
- # Step 2: Must be a Response object
- if not isinstance(result, Response):
- if strict_response_validation:
- raise serializers.ValidationError(
- f"View must return a Response object when using @validated_request with response serializers. Got {type(result).__name__}"
- )
- elif settings.DEBUG:
- logger.warning(
- "View must return a Response object when using @validated_request with response serializers. Please update the provided API schema to ensure API docs remain up to date",
- view_func=view_func.__name__,
- result_type=type(result).__name__,
- )
- return result
-
- status_code = result.status_code
- data = result.data
-
- # Step 3: Check if status code is in defined responses
- if status_code not in responses:
- if strict_response_validation:
- raise serializers.ValidationError(
- f"Response status code {status_code} not declared in responses parameter of the @validated_request decorator. "
- f"Declared status codes: {sorted(responses.keys())}"
- )
- elif settings.DEBUG:
- logger.warning(
- "Response status code not declared in responses parameter of the @validated_request decorator. Please update the provided API schema to ensure API docs remain up to date",
- view_func=view_func.__name__,
- status_code=status_code,
- declared_status_codes=sorted(responses.keys()),
- )
- return result
-
- # Step 4: Check if there's a serializer (or if it's declared as None)
- response_config = responses[status_code]
- is_none = response_config is None or (
- hasattr(response_config, "response") and response_config.response is None
- )
-
- if is_none:
- # Declared as None - validate no body
- if data not in (None, {}, []):
- if strict_response_validation:
- raise serializers.ValidationError(
- f"Response status code {status_code} is declared with no body, but response contains data"
- )
- elif settings.DEBUG:
- logger.warning(
- f"Response status code {status_code} is declared with no body, but response contains data. Please update the provided API schema to ensure API docs remain up to date",
- view_func=view_func.__name__,
- status_code=status_code,
- )
- return result
-
- # Step 5: Validate response matches serializer
-
- if strict_response_validation or settings.DEBUG:
- if response_config is None:
- return result
- response_serializer = response_config.response
- # A PolymorphicProxySerializer only describes the schema; it cannot validate data.
- # `many=True` wraps one in a plain ListSerializer, so the child needs the same check.
- declares_polymorphic_proxy = isinstance(response_serializer, PolymorphicProxySerializer) or isinstance(
- getattr(response_serializer, "child", None), PolymorphicProxySerializer
- )
- if response_serializer is None or declares_polymorphic_proxy:
- return result
-
- context: dict[str, Any] = getattr(self, "get_serializer_context", lambda: {})()
- serialized: serializers.BaseSerializer[Any]
-
- serializer_class: type[serializers.BaseSerializer[Any]]
-
- # Handle both class and instance to match DRF Spectacular's behavior
- if isinstance(response_serializer, serializers.ListSerializer):
- # ListSerializer wraps the real serializer - reconstruct with child
- child = cast(serializers.Serializer, response_serializer.child)
- serializer_class = type(response_serializer)
- serialized = type(response_serializer)(data=data, child=type(child)(), context=context)
- elif isinstance(response_serializer, serializers.Serializer):
- serializer_class = type(response_serializer)
- serialized = type(response_serializer)(data=data, context=context)
- else:
- serializer_class = response_serializer
- serialized = response_serializer(data=data, context=context)
-
- try:
- response_matches_serializer = serialized.is_valid(raise_exception=strict_response_validation)
- except Exception as exc:
- # `is_valid` only handles DRF's ValidationError. A DataclassSerializer can raise other
- # errors for a valid response, and this check is advisory under DEBUG, so warn instead.
- if strict_response_validation:
- raise
- logger.warning(
- "Response serializer could not parse the response it declared for status code "
- f"{status_code} in the responses parameter of the @validated_request decorator. "
- "The response was returned unchanged; check the declared serializer.",
- view_func=view_func.__name__,
- status_code=status_code,
- serializer_class=serializer_class.__name__,
- error=str(exc),
- )
- return result
-
- if not response_matches_serializer:
- logger.warning(
- f"Response data does not match declared serializer for status code {status_code} declared in responses parameter of the @validated_request decorator. Please update the provided API schema to ensure API docs remain up to date",
- view_func=view_func.__name__,
- status_code=status_code,
- serializer_class=serializer_class.__name__,
- validation_errors=serialized.errors,
- )
-
+ response_validator.check(self, result)
return result
return wrapper
diff --git a/posthog/api/test/test_mixins.py b/posthog/api/test/test_mixins.py
index 876cbcfe7342..a3c0f72018ca 100644
--- a/posthog/api/test/test_mixins.py
+++ b/posthog/api/test/test_mixins.py
@@ -41,6 +41,14 @@ class RaisingResponseSerializer(serializers.Serializer):
raise RuntimeError("boom")
+class RequiresFlavorSerializer(serializers.Serializer):
+ value = serializers.CharField()
+
+ def __init__(self, *args, flavor: str, **kwargs):
+ self.flavor = flavor
+ super().__init__(*args, **kwargs)
+
+
class TestValidatedRequestDecorator(SimpleTestCase):
def test_request_validation_with_valid_event_data(self):
"""All valid data, should return 200 OK"""
@@ -171,18 +179,25 @@ class TestValidatedRequestDecorator(SimpleTestCase):
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
assert response.data["type"] == "server_error"
- def test_invalid_response_data_logs_warning(self):
+ @parameterized.expand(
+ [
+ ("class", EventCaptureResponseSerializer, {"wrong_field": "value"}, "EventCaptureResponseSerializer"),
+ ("instance", EventCaptureResponseSerializer(), {"wrong_field": "value"}, "EventCaptureResponseSerializer"),
+ ("many", EventCaptureResponseSerializer(many=True), [{"wrong_field": "value"}], "ListSerializer"),
+ ]
+ )
+ def test_invalid_response_data_logs_warning(self, _name, declared_response, response_data, serializer_class_name):
"""Invalid response data, should log warning and return response"""
@validated_request(
request_serializer=EventCaptureRequestSerializer,
responses={
- 200: OpenApiResponse(response=EventCaptureResponseSerializer),
+ 200: OpenApiResponse(response=declared_response),
},
)
def mock_endpoint(view_self, request):
# Missing required fields in response
- return Response({"wrong_field": "value"}, status=status.HTTP_200_OK)
+ return Response(response_data, status=status.HTTP_200_OK)
view_instance = Mock()
view_instance.get_serializer_context = Mock(return_value={})
@@ -205,11 +220,53 @@ class TestValidatedRequestDecorator(SimpleTestCase):
)
assert call_args[1]["view_func"] == "mock_endpoint"
assert call_args[1]["status_code"] == 200
- assert call_args[1]["serializer_class"] == "EventCaptureResponseSerializer"
+ assert call_args[1]["serializer_class"] == serializer_class_name
assert "validation_errors" in call_args[1]
assert response.status_code == status.HTTP_200_OK
- assert response.data["wrong_field"] == "value"
+ assert response.data == response_data
+
+ @override_settings(DEBUG=True)
+ def test_declared_serializer_instance_keeps_its_constructor_options(self):
+ declared = EventCaptureResponseSerializer(many=True, allow_empty=False)
+
+ @validated_request(responses={200: OpenApiResponse(response=declared)})
+ def mock_endpoint(view_self, request):
+ return Response([], status=status.HTTP_200_OK)
+
+ view_instance = Mock()
+ view_instance.get_serializer_context = Mock(return_value={})
+ mock_request = Mock()
+ mock_request._full_data = {}
+ mock_request.data = {}
+
+ with patch("posthog.api.mixins.logger") as mock_logger:
+ response = mock_endpoint(view_instance, mock_request)
+
+ mock_logger.warning.assert_called_once()
+ assert "Response data does not match declared serializer" in mock_logger.warning.call_args[0][0]
+
+ assert response.status_code == status.HTTP_200_OK
+ assert not hasattr(declared, "initial_data")
+
+ def test_declared_serializer_instance_with_a_required_constructor_argument(self):
+ @validated_request(
+ responses={200: OpenApiResponse(response=RequiresFlavorSerializer(flavor="vanilla"))},
+ strict_response_validation=True,
+ )
+ def mock_endpoint(view_self, request):
+ return Response({"value": "ok"}, status=status.HTTP_200_OK)
+
+ view_instance = Mock()
+ view_instance.get_serializer_context = Mock(return_value={})
+ mock_request = Mock()
+ mock_request._full_data = {}
+ mock_request.data = {}
+
+ response = mock_endpoint(view_instance, mock_request)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.data["value"] == "ok"
def test_response_serializer_that_raises_while_parsing_logs_warning(self):
@validated_request(
@@ -281,6 +338,29 @@ class TestValidatedRequestDecorator(SimpleTestCase):
assert response.status_code == status.HTTP_200_OK
assert response.data["custom_response"] == "anything goes"
+ with patch("posthog.api.mixins.settings") as mock_settings:
+ mock_settings.DEBUG = True
+ with patch("posthog.api.mixins.logger") as mock_logger:
+ mock_endpoint(view_instance, mock_request)
+
+ mock_logger.warning.assert_called_once()
+ assert "No responses parameter defined" in mock_logger.warning.call_args[0][0]
+
+ def test_strict_response_validation_without_responses_raises(self):
+ @validated_request(strict_response_validation=True)
+ def mock_endpoint(view_self, request):
+ return Response({"anything": True}, status=status.HTTP_200_OK)
+
+ view_instance = Mock()
+ mock_request = Mock()
+ mock_request._full_data = {}
+ mock_request.data = {}
+
+ with pytest.raises(serializers.ValidationError) as exc_info:
+ mock_endpoint(view_instance, mock_request)
+
+ assert "Responses parameter is required when strict_response_validation is True" in str(exc_info.value)
+
@parameterized.expand(
[
("single", False, {"anything": True}),
@@ -609,6 +689,7 @@ class TestValidatedRequestDecorator(SimpleTestCase):
assert response.data["distinct_id"] == "user_123"
assert mock_request.data["event"] == "$pageview"
+ @override_settings(DEBUG=True)
def test_no_body_response_declared_as_none_succeeds(self):
"""When status code is declared as None (no body), response with no body should succeed"""
@@ -625,7 +706,10 @@ class TestValidatedRequestDecorator(SimpleTestCase):
mock_request._full_data = {}
mock_request.data = {}
- response = mock_endpoint(view_instance, mock_request)
+ with patch("posthog.api.mixins.logger") as mock_logger:
+ response = mock_endpoint(view_instance, mock_request)
+
+ mock_logger.warning.assert_not_called()
assert response.status_code == status.HTTP_204_NO_CONTENT
assert response.data is None