: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): add external API to write account custom property values (#66345)
Arthur Moreira de Deusb6eebcb4ca79
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex ff2c0f3f750e..8bead7bef273 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -352,6 +352,57 @@ def update_external_account(return contracts.ExternalAccountUpdateResult(account=_to_external_account(account))+def set_external_account_custom_properties(+ team_id: int,+ external_id: str,+ *,+ properties: dict[str, Any],+ created_by_id: int | None = None,+) -> contracts.ExternalAccountCustomPropertiesResult:+ """Set custom property values on an account by definition id, for the external API.++ Resolves the account by external id, then applies every ``{definition_id: value}`` pair+ transactionally — a bad value or unknown definition rolls the whole batch back. Returns a result+ the view maps to the exact HTTP status/body: account not found, unknown definition, invalid+ value, a concurrent-write conflict, a generic write failure, or success carrying the set values.+ """+ account = _get_external_account_by_external_id(team_id, external_id)+ if account is None:+ return contracts.ExternalAccountCustomPropertiesResult(+ error=contracts.ExternalAccountCustomPropertiesError.ACCOUNT_NOT_FOUND+ )++ try:+ with transaction.atomic():+ rows = _custom_property_values_logic.set_account_custom_properties_by_id(+ team_id=team_id,+ account_id=account.id,+ properties=properties,+ created_by_id=created_by_id,+ )+ except _custom_property_values_logic.CustomPropertyDefinitionNotFound as exc:+ return contracts.ExternalAccountCustomPropertiesResult(+ error=contracts.ExternalAccountCustomPropertiesError.DEFINITION_NOT_FOUND,+ error_field=str(exc.identifier),+ )+ except _custom_property_values_logic.InvalidCustomPropertyValue as exc:+ return contracts.ExternalAccountCustomPropertiesResult(+ error=contracts.ExternalAccountCustomPropertiesError.INVALID_VALUE,+ error_field=exc.field,+ )+ except _custom_property_values_logic.CustomPropertyValueConflict:+ return contracts.ExternalAccountCustomPropertiesResult(+ error=contracts.ExternalAccountCustomPropertiesError.CONFLICT+ )+ except Exception as e:+ capture_exception(e, {"external_id": external_id})+ return contracts.ExternalAccountCustomPropertiesResult(+ error=contracts.ExternalAccountCustomPropertiesError.UPDATE_FAILED+ )++ return contracts.ExternalAccountCustomPropertiesResult(values=[_to_custom_property_value(row) for row in rows])++# ---------------------------------------------------------------------------# Presentation wave: account / customer-journey / profile-config CRUD.#@@ -628,7 +679,9 @@ def list_custom_property_definitions(def get_custom_property_definition(team_id: int, definition_id: str) -> contracts.CustomPropertyDefinitionView | None:definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)- return _to_custom_property_definition_view(definition) if definition is not None else None+ if definition is None:+ return None+ return _to_custom_property_definition_view(definition)def create_custom_property_definition(diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 6e6d5bd61bdc..c46317d94de6 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -339,3 +339,28 @@ class CustomPropertyValue:value: float | bool | str | datetime | Nonecreated_at: datetimecreated_by_id: int | None+++class ExternalAccountCustomPropertiesError(Enum):+ """Failure modes of the external custom-property write, each mapping to a distinct+ HTTP response in the view."""++ ACCOUNT_NOT_FOUND = "account_not_found"+ DEFINITION_NOT_FOUND = "definition_not_found"+ INVALID_VALUE = "invalid_value"+ CONFLICT = "conflict"+ UPDATE_FAILED = "update_failed"+++@dataclass(frozen=True)+class ExternalAccountCustomPropertiesResult:+ """Outcome of the external custom-property write, modeled so the view can map each+ case to its exact HTTP status and error string without holding write logic.++ Exactly one of ``values`` / ``error`` is set. ``error_field`` carries the offending+ property name for ``DEFINITION_NOT_FOUND`` / ``INVALID_VALUE`` failures; it is None otherwise.+ """++ values: list[CustomPropertyValue] | None = None+ error: ExternalAccountCustomPropertiesError | None = None+ error_field: str | None = Nonediff --git a/products/customer_analytics/backend/logic/custom_property_values.py b/products/customer_analytics/backend/logic/custom_property_values.pyindex cb024822b73f..a02a43d61efe 100644--- a/products/customer_analytics/backend/logic/custom_property_values.py+++ b/products/customer_analytics/backend/logic/custom_property_values.py@@ -11,6 +11,7 @@ from datetime import UTC, date, datetimefrom typing import Anyfrom uuid import UUID+from django.core.exceptions import ValidationErrorfrom django.db import IntegrityError, transactionfrom django.utils import timezone@@ -21,11 +22,25 @@ CoercedValue = float | bool | str | datetimeclass InvalidCustomPropertyValue(ValueError):- """Raised when a value can't be coerced to its definition's data type."""+ """Raised when a value can't be coerced to its definition's data type.++ ``field`` carries the definition id when set from a batch write, so the caller can+ point at which property failed.+ """++ field: str | None = Noneclass CustomPropertyDefinitionNotFound(Exception):- """Raised when the target custom property definition does not exist for the team."""+ """Raised when the target custom property definition does not exist for the team.++ ``identifier`` is the id or name that failed to resolve, so callers can surface which+ property was at fault.+ """++ def __init__(self, identifier: Any) -> None:+ super().__init__(f"Custom property definition '{identifier}' not found.")+ self.identifier = identifierclass CustomPropertyValueConflict(Exception):@@ -58,21 +73,67 @@ def set_custom_property_value(try:definition = CustomPropertyDefinition.objects.for_team(team_id).get(id=definition_id)except CustomPropertyDefinition.DoesNotExist as exc:- raise CustomPropertyDefinitionNotFound(- f"Custom property definition {definition_id} not found for team {team_id}."- ) from exc+ raise CustomPropertyDefinitionNotFound(definition_id) from exc_assert_account_in_team(team_id=team_id, account_id=account_id)- column, coerced = _coerce_to_column(definition, value)+ return _set_value(+ team_id=team_id, account_id=account_id, definition=definition, value=value, created_by_id=created_by_id+ )+++def set_account_custom_properties_by_id(+ *,+ team_id: int,+ account_id: str | UUID,+ properties: dict[str, Any],+ created_by_id: int | None = None,+) -> list[CustomPropertyValue]:+ """Set several of an account's custom property values, addressing each by definition id.+ Resolves each id to its team-scoped definition, then applies the same coerce + soft-delete ++ insert as `set_custom_property_value`. Caller is responsible for wrapping the batch in a+ transaction when all-or-nothing semantics are required.++ Raises `CustomPropertyDefinitionNotFound` (unknown id, carrying the id),+ `InvalidCustomPropertyValue` (value doesn't match the data type, carrying the id in `field`),+ `Account.DoesNotExist`, or `CustomPropertyValueConflict`.+ """+ _assert_account_in_team(team_id=team_id, account_id=account_id)+ rows: list[CustomPropertyValue] = []+ for definition_id, value in properties.items():+ try:+ definition = CustomPropertyDefinition.objects.for_team(team_id).get(id=definition_id)+ except (CustomPropertyDefinition.DoesNotExist, ValidationError) as exc:+ raise CustomPropertyDefinitionNotFound(definition_id) from exc+ try:+ row = _set_value(+ team_id=team_id, account_id=account_id, definition=definition, value=value, created_by_id=created_by_id+ )+ except InvalidCustomPropertyValue as exc:+ exc.field = str(definition_id)+ raise+ rows.append(row)+ return rows+++def _set_value(+ *,+ team_id: int,+ account_id: str | UUID,+ definition: CustomPropertyDefinition,+ value: Any,+ created_by_id: int | None,+) -> CustomPropertyValue:+ """Coerce `value` and atomically supersede the account's active row for `definition`."""+ column, coerced = _coerce_to_column(definition, value)try:with transaction.atomic():CustomPropertyValue.objects.for_team(team_id).filter(- account_id=account_id, definition_id=definition_id, is_deleted=False+ account_id=account_id, definition_id=definition.id, is_deleted=False).update(is_deleted=True)row = CustomPropertyValue.objects.for_team(team_id).create(team_id=team_id,account_id=account_id,- definition_id=definition_id,+ definition_id=definition.id,created_by_id=created_by_id,**{column: coerced},)diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.pyindex 17d799dd982c..3f068c9546e0 100644--- a/products/customer_analytics/backend/presentation/views/external.py+++ b/products/customer_analytics/backend/presentation/views/external.py@@ -17,6 +17,8 @@ from django.db.models import Qimport structlogimport posthoganalytics+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import extend_schema, extend_schema_fieldfrom rest_framework import serializers, statusfrom rest_framework.permissions import AllowAnyfrom rest_framework.request import Request@@ -216,3 +218,98 @@ class ExternalAccountView(APIView):return _update_error_response(result)return Response(_external_account_body(result.account))+++@extend_schema_field({"oneOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}]})+class _CustomPropertyScalarField(serializers.Field):+ """A custom property value sent over the external API — a JSON scalar.++ Objects, arrays, and null are rejected here; the concrete type each property accepts is set by+ its definition and validated server-side when the value is coerced.+ """++ def to_internal_value(self, data: Any) -> Any:+ if data is None or isinstance(data, dict | list):+ raise serializers.ValidationError("Value must be a string, number, or boolean.")+ return data+++class ExternalAccountCustomPropertiesSerializer(serializers.Serializer):+ external_id = serializers.CharField(+ max_length=400,+ help_text="External ID of the account whose custom property values to set — the group key it is linked to.",+ )+ properties = serializers.DictField(+ child=_CustomPropertyScalarField(),+ help_text="Map of custom property definition UUID to the value to set for this account.",+ )+++_CUSTOM_PROPERTIES_ERROR_RESPONSES = {+ contracts.ExternalAccountCustomPropertiesError.ACCOUNT_NOT_FOUND: ("Account not found", status.HTTP_404_NOT_FOUND),+ contracts.ExternalAccountCustomPropertiesError.DEFINITION_NOT_FOUND: (+ "Custom property definition not found",+ status.HTTP_400_BAD_REQUEST,+ ),+ contracts.ExternalAccountCustomPropertiesError.INVALID_VALUE: (+ "Invalid custom property value",+ status.HTTP_400_BAD_REQUEST,+ ),+ contracts.ExternalAccountCustomPropertiesError.CONFLICT: (+ "A concurrent write set this property — retry",+ status.HTTP_409_CONFLICT,+ ),+ contracts.ExternalAccountCustomPropertiesError.UPDATE_FAILED: (+ "Failed to update custom properties",+ status.HTTP_500_INTERNAL_SERVER_ERROR,+ ),+}+++def _custom_properties_error_response(result: contracts.ExternalAccountCustomPropertiesResult) -> Response:+ assert result.error is not None+ message, code = _CUSTOM_PROPERTIES_ERROR_RESPONSES[result.error]+ if result.error_field:+ message = f"{result.error_field}: {message}"+ return Response({"error": message}, status=code)+++class ExternalAccountCustomPropertiesView(APIView):+ """+ PATCH /api/customer_analytics/external/account/custom_property_values — Set an account's custom+ property values, addressing each property by its definition id (UUID).++ Authenticated via Bearer token (team secret_api_token) in the Authorization header.+ """++ authentication_classes: list = []+ permission_classes = [AllowAny]+ throttle_classes = [ExternalAccountBurstThrottle, ExternalAccountSustainedThrottle]++ @extend_schema(request=ExternalAccountCustomPropertiesSerializer, responses={200: OpenApiTypes.OBJECT})+ def patch(self, request: Request) -> Response:+ team, error = _authenticate_team(request)+ if error:+ return error++ assert team is not None++ serializer = ExternalAccountCustomPropertiesSerializer(data=request.data)+ if not serializer.is_valid():+ return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)+ data = serializer.validated_data++ external_id = data["external_id"].strip()+ if not external_id:+ return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)++ result = facade.set_external_account_custom_properties(team.id, external_id, properties=data["properties"])+ if result.values is None:+ return _custom_properties_error_response(result)++ return Response(+ {+ "external_id": external_id,+ "values": [{"definition_id": str(v.definition_id), "value": v.value} for v in result.values],+ }+ )diff --git a/products/customer_analytics/backend/presentation/views/urls.py b/products/customer_analytics/backend/presentation/views/urls.pyindex 1c2e07b884a4..9cf7bebc9973 100644--- a/products/customer_analytics/backend/presentation/views/urls.py+++ b/products/customer_analytics/backend/presentation/views/urls.py@@ -2,8 +2,16 @@from django.urls import path-from products.customer_analytics.backend.presentation.views.external import ExternalAccountView+from products.customer_analytics.backend.presentation.views.external import (+ ExternalAccountCustomPropertiesView,+ ExternalAccountView,+)urlpatterns = [path("external/account", ExternalAccountView.as_view(), name="external-account"),+ path(+ "external/account/custom_property_values",+ ExternalAccountCustomPropertiesView.as_view(),+ name="external-account-custom-property-values",+ ),]diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.pyindex e17a1c8c16b3..48bbe4c26ccc 100644--- a/products/customer_analytics/backend/test/test_custom_property_values.py+++ b/products/customer_analytics/backend/test/test_custom_property_values.py@@ -21,6 +21,7 @@ from products.customer_analytics.backend.logic.custom_property_values import (CustomPropertyValueConflict,InvalidCustomPropertyValue,list_active_custom_property_values,+ set_account_custom_properties_by_id,set_custom_property_value,)from products.customer_analytics.backend.models import (@@ -194,6 +195,43 @@ class TestSetCustomPropertyValue(BaseTest):self._set(definition=definition, value="enterprise")+class TestSetAccountCustomPropertiesById(BaseTest):+ def setUp(self):+ super().setUp()+ self.account = create_account(team_id=self.team.id)++ def test_sets_multiple_values_resolving_each_definition_by_id(self):+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan", display_type=DisplayType.TEXT)+ seats = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER)++ rows = set_account_custom_properties_by_id(+ team_id=self.team.id,+ account_id=self.account.id,+ properties={str(plan.id): "enterprise", str(seats.id): "42"},+ )++ assert {(r.definition_id, r.value_str, r.value_num) for r in rows} == {+ (plan.id, "enterprise", None),+ (seats.id, None, 42.0),+ }++ def test_unknown_id_raises_carrying_the_id(self):+ missing = uuid4()+ with pytest.raises(CustomPropertyDefinitionNotFound) as exc_info:+ set_account_custom_properties_by_id(+ team_id=self.team.id, account_id=self.account.id, properties={str(missing): "x"}+ )+ assert exc_info.value.identifier == str(missing)++ def test_invalid_value_raises_carrying_the_id(self):+ seats = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER)+ with pytest.raises(InvalidCustomPropertyValue) as exc_info:+ set_account_custom_properties_by_id(+ team_id=self.team.id, account_id=self.account.id, properties={str(seats.id): "not a number"}+ )+ assert exc_info.value.field == str(seats.id)++class TestCustomPropertyValueFacade(BaseTest):def setUp(self):super().setUp()@@ -237,3 +275,54 @@ class TestCustomPropertyValueFacade(BaseTest):assert isinstance(result[0], contracts.CustomPropertyValue)assert result[0].value == "enterprise"assert result[0].definition_id == plan.id+++class TestSetExternalAccountCustomProperties(BaseTest):+ def setUp(self):+ super().setUp()+ self.account = create_account(team_id=self.team.id, external_id="acme-1")++ def test_sets_values_by_id_and_returns_contracts(self):+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan", display_type=DisplayType.TEXT)+ seats = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER)++ result = facade.set_external_account_custom_properties(+ self.team.id, "acme-1", properties={str(plan.id): "enterprise", str(seats.id): 42}+ )++ assert result.error is None+ assert result.values is not None+ assert {(v.value) for v in result.values} == {"enterprise", 42.0}++ def test_unknown_external_id_returns_account_not_found(self):+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan")+ result = facade.set_external_account_custom_properties(self.team.id, "missing", properties={str(plan.id): "x"})+ assert result.error == contracts.ExternalAccountCustomPropertiesError.ACCOUNT_NOT_FOUND++ def test_maps_unknown_definition_to_error_with_offending_id(self):+ missing = uuid4()+ result = facade.set_external_account_custom_properties(self.team.id, "acme-1", properties={str(missing): "x"})+ assert result.values is None+ assert result.error == contracts.ExternalAccountCustomPropertiesError.DEFINITION_NOT_FOUND+ assert result.error_field == str(missing)++ def test_maps_invalid_value_to_error_with_offending_id(self):+ seats = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER)+ result = facade.set_external_account_custom_properties(+ self.team.id, "acme-1", properties={str(seats.id): "abc"}+ )+ assert result.values is None+ assert result.error == contracts.ExternalAccountCustomPropertiesError.INVALID_VALUE+ assert result.error_field == str(seats.id)++ def test_batch_is_all_or_nothing(self):+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan", display_type=DisplayType.TEXT)+ seats = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER)++ result = facade.set_external_account_custom_properties(+ self.team.id, "acme-1", properties={str(plan.id): "enterprise", str(seats.id): "not a number"}+ )++ assert result.error == contracts.ExternalAccountCustomPropertiesError.INVALID_VALUE+ # The good "Plan" write must roll back with the failed "Seats" write — nothing persists.+ assert not CustomPropertyValue.objects.for_team(self.team.id).filter(account=self.account).exists()diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.pyindex a6a1539fe956..765df490b252 100644--- a/products/customer_analytics/backend/test/test_external.py+++ b/products/customer_analytics/backend/test/test_external.py@@ -1,3 +1,5 @@+from uuid import uuid4+from posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -8,8 +10,9 @@ from rest_framework.test import APIClientfrom posthog.models import Organization, Team, Userfrom posthog.models.utils import generate_random_token_secret+from products.customer_analytics.backend.models import CustomPropertyValue, DisplayTypefrom products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties-from products.customer_analytics.backend.test.factories import create_account+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definitionclass TestExternalAccountAPI(APIBaseTest):@@ -214,3 +217,60 @@ class TestExternalAccountAPI(APIBaseTest):self.account.refresh_from_db()self.assertEqual(self.account.external_id, "acme-1")self.assertEqual(self.account.name, "Acme Corp")+++class TestExternalAccountCustomPropertiesAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.team.secret_api_token = generate_random_token_secret()+ self.team.save(update_fields=["secret_api_token"])+ self.client = APIClient()+ self.account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")+ self.plan = create_custom_property_definition(team_id=self.team.id, name="Plan", display_type=DisplayType.TEXT)+ self.seats = create_custom_property_definition(+ team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER+ )+ self.url = "/api/customer_analytics/external/account/custom_property_values"+ csp_enabled = patch(+ "products.customer_analytics.backend.presentation.views.external.posthoganalytics.feature_enabled",+ return_value=True,+ )+ csp_enabled.start()+ self.addCleanup(csp_enabled.stop)++ def _auth_headers(self, token=None):+ return {"HTTP_AUTHORIZATION": f"Bearer {token or self.team.secret_api_token}"}++ def _patch(self, payload, token=None):+ return self.client.patch(self.url, data=payload, format="json", **self._auth_headers(token))++ def test_requires_auth(self):+ response = self.client.patch(self.url, data={"external_id": "acme-1", "properties": {}}, format="json")+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_sets_values_by_definition_id(self):+ response = self._patch(+ {"external_id": "acme-1", "properties": {str(self.plan.id): "enterprise", str(self.seats.id): 42}}+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ active = CustomPropertyValue.objects.for_team(self.team.id).filter(account=self.account, is_deleted=False)+ self.assertEqual(+ {(v.definition.name, v.value_str, v.value_num) for v in active},+ {+ ("Plan", "enterprise", None),+ ("Seats", None, 42.0),+ },+ )++ def test_unknown_external_id_returns_404(self):+ response = self._patch({"external_id": "missing", "properties": {str(self.plan.id): "x"}})+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_unknown_definition_id_returns_400(self):+ response = self._patch({"external_id": "acme-1", "properties": {str(uuid4()): "x"}})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_rejects_non_scalar_value(self):+ response = self._patch({"external_id": "acme-1", "properties": {str(self.plan.id): {"nested": "object"}}})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)