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.

refactor(experiments): move the web experiments API into the product (#126286)

Andersa297b8c0888b
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index 41b970ef2a63..16750d511fbf 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -428,7 +428,6 @@ from posthog.api.cohort import CohortViewSet, LegacyCohortViewSet # noqa: E402
from posthog.api.element import ElementViewSet, LegacyElementViewSet # noqa: E402
from posthog.api.event import EventViewSet, LegacyEventViewSet # noqa: E402
from posthog.api.person import LegacyPersonViewSet, PersonViewSet # noqa: E402
-from posthog.api.web_experiment import WebExperimentViewSet # noqa: E402
# Legacy endpoints CH (to be removed eventually)
router.register(r"cohort", LegacyCohortViewSet, basename="cohort")
@@ -437,7 +436,6 @@ router.register(r"event", LegacyEventViewSet, basename="event")
# Nested endpoints CH
projects_router.register(r"events", EventViewSet, "project_events", ["team_id"])
-projects_router.register(r"web_experiments", WebExperimentViewSet, "web_experiments", ["project_id"])
projects_router.register(r"cohorts", CohortViewSet, "project_cohorts", ["project_id"])
projects_router.register(
diff --git a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
index d9a603530e00..02436a23777a 100644
--- a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
+++ b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
@@ -90,7 +90,6 @@ REVIEWED_WRITABLE: dict[str, str] = {
"posthog.api.event_definition.EventDefinitionSerializer.last_seen_at": "TODO: server-owned ingestion telemetry, make read-only",
"posthog.api.health_issue.HealthIssueSerializer.snoozed_until": "TODO: server-derived. SnoozeDurationField accepts only a relative duration such as '7d' and computes the stored instant",
"posthog.api.my_notifications.MyNotificationsSerializer.created_at": "TODO: server-owned activity log timestamp, make read-only",
- "posthog.api.web_experiment.WebExperimentsAPISerializer.created_at": "TODO: server-owned creation timestamp, make read-only",
"posthog.session_recordings.session_recording_api.SessionRecordingSharedSerializer.end_time": "TODO: server-owned, derived from the ingested replay events",
"posthog.session_recordings.session_recording_api.SessionRecordingSharedSerializer.start_time": "TODO: server-owned, derived from the ingested replay events",
"products.actions.backend.api.action.ActionSerializer.last_calculated_at": "TODO: server-owned, written by the action calculation job",
@@ -107,6 +106,7 @@ REVIEWED_WRITABLE: dict[str, str] = {
"products.experiments.backend.presentation.serializers.ExperimentSerializer.start_date": "Client launches the experiment by setting this",
"products.experiments.backend.presentation.serializers.ExperimentWriteSerializer.end_date": "Client stops the experiment by setting this",
"products.experiments.backend.presentation.serializers.ExperimentWriteSerializer.start_date": "Client launches the experiment by setting this",
+ "products.experiments.backend.presentation.web_experiments.WebExperimentsAPISerializer.created_at": "TODO: server-owned creation timestamp, make read-only",
"products.feature_flags.backend.api.scheduled_change.ScheduledChangeSerializer.end_date": "Client picks when a recurring schedule stops",
"products.feature_flags.backend.api.scheduled_change.ScheduledChangeSerializer.scheduled_at": "Client picks when the change is applied",
"products.groups.backend.presentation.views.GroupTypeSerializer.created_at": "TODO: server-owned, the model sets it on creation itself",
diff --git a/posthog/urls.py b/posthog/urls.py
index 61c9152032eb..15f4b88859ed 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -30,7 +30,6 @@ from posthog.api.oauth.toolbar_views import authorize_and_redirect
from posthog.api.scim import views as scim_views
from posthog.api.sdk_health import sdk_health
from posthog.api.two_factor_qrcode import CacheAwareQRGeneratorView
-from posthog.api.web_experiment import web_experiments
from posthog.ee_urls import ee_urlpatterns
from posthog.frontend_views import app_context, home, home_with_region_redirect
from posthog.ingress.github.provider import build_github_provider
@@ -50,6 +49,7 @@ from products.customer_analytics.backend.presentation.views.internal import (
InternalAccountView as CustomerAnalyticsInternalAccountView,
)
from products.early_access_features.backend.api import early_access_features
+from products.experiments.backend.routes import web_experiments
from products.messaging.backend.presentation.views.customerio_webhook import CustomerIOWebhookView
from products.messaging.backend.presentation.views.recipient_preferences import preferences_page, update_preferences
from products.notebooks.backend.facade.sql_v2 import (
diff --git a/posthog/api/web_experiment.py b/products/experiments/backend/presentation/web_experiments.py
similarity index 97%
rename from posthog/api/web_experiment.py
rename to products/experiments/backend/presentation/web_experiments.py
index d4341eb18336..3aa1d65a9b44 100644
--- a/posthog/api/web_experiment.py
+++ b/products/experiments/backend/presentation/web_experiments.py
@@ -5,6 +5,7 @@ from django.http import HttpResponse, JsonResponse
from django.utils.text import slugify
from django.views.decorators.csrf import csrf_exempt
+from drf_spectacular.utils import extend_schema
from nanoid import generate
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
@@ -255,6 +256,9 @@ class WebExperimentsAPISerializer(serializers.ModelSerializer):
return feature_flag_key
+# Codegen routes an endpoint by its x-product. Only the toolbar calls these routes, through its own
+# client, and "web_experiments" names no product folder, so the generated clients leave them out.
+@extend_schema(extensions={"x-product": "web_experiments"})
class WebExperimentViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "experiment"
serializer_class = WebExperimentsAPISerializer
diff --git a/products/experiments/backend/routes.py b/products/experiments/backend/routes.py
index 926772c543a0..7c0907a41d67 100644
--- a/products/experiments/backend/routes.py
+++ b/products/experiments/backend/routes.py
@@ -1,11 +1,21 @@
from posthog.api.routing import RouterRegistry
from posthog.settings import EE_AVAILABLE
+from products.experiments.backend.presentation.web_experiments import WebExperimentViewSet, web_experiments
+
+# posthog-js calls `web_experiments` at `api/web_experiments`, which is outside the `api/experiments/`
+# mount that `api_urlpatterns` gets. So `posthog/urls.py` keeps that path. It imports the view from here
+# because the `tach.toml` interface exposes `backend.routes` but not `backend.presentation.web_experiments`.
+__all__ = ["register_routes", "web_experiments"]
+
def register_routes(routers: RouterRegistry) -> None:
- # All experiments viewsets currently live in `ee/clickhouse/views/` and
- # `products/experiments/backend/presentation/views.py` — both unavailable
- # without EE installed, so the entire surface is EE-gated.
+ # The web experiments API does not need EE, so it registers before the EE gate.
+ routers.projects.register(r"web_experiments", WebExperimentViewSet, "web_experiments", ["project_id"])
+
+ # The other experiments viewsets live in `ee/clickhouse/views/` and
+ # `products/experiments/backend/presentation/views.py`. Both are unavailable
+ # without EE installed, so these routes are EE-gated.
if not EE_AVAILABLE:
return
diff --git a/posthog/api/test/test_web_experiment.py b/products/experiments/backend/test/test_web_experiments.py
similarity index 99%
rename from posthog/api/test/test_web_experiment.py
rename to products/experiments/backend/test/test_web_experiments.py
index 35389ebe9791..8e6a1b6ed99f 100644
--- a/posthog/api/test/test_web_experiment.py
+++ b/products/experiments/backend/test/test_web_experiments.py
@@ -10,10 +10,10 @@ from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
-from posthog.api.web_experiment import WebExperimentsAPISerializer, WebExperimentViewSet
from posthog.models.activity_logging.activity_log import ActivityLog
from products.experiments.backend.models.web_experiment import WebExperiment
+from products.experiments.backend.presentation.web_experiments import WebExperimentsAPISerializer, WebExperimentViewSet
class TestWebExperiment(APIBaseTest):
@@ -85,7 +85,7 @@ class TestWebExperiment(APIBaseTest):
request=ANY,
)
- @patch("posthog.api.web_experiment.report_user_action")
+ @patch("products.experiments.backend.presentation.web_experiments.report_user_action")
def test_web_experiment_creation_reports_experiment_created(self, mock_report_user_action):
response = self._create_web_experiment()
response_data = response.json()
diff --git a/pyproject.toml b/pyproject.toml
index 811dd1c11e1a..4356235275b2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -751,6 +751,11 @@ ignore_imports = [
"products.experiments.backend.presentation.views -> products.experiments.backend.setup_context",
"products.experiments.backend.presentation.views -> products.feature_flags.backend.models.evaluation_context",
"products.experiments.backend.presentation.views -> products.feature_flags.backend.models.feature_flag",
+ # TODO: the web experiments API still reads the experiments models directly. Thin it to
+ # parse -> facade -> serialize and delete these entries.
+ "products.experiments.backend.presentation.web_experiments -> products.experiments.backend.models.experiment",
+ "products.experiments.backend.presentation.web_experiments -> products.experiments.backend.models.team_experiments_config",
+ "products.experiments.backend.presentation.web_experiments -> products.experiments.backend.models.web_experiment",
# TODO: data_warehouse presentation wave — the structural move landed the viewsets under
# presentation/views/ but they still reach in-product internals and sibling products
# (warehouse_sources, data_modeling, data_tools, cdp, revenue_analytics, batch_exports)