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(devex): declare path ids through path_parameters in six products (#127201)

Julian Bezc99b035fddf6
diff --git a/products/batch_exports/backend/presentation/views/batch_export/backfills.py b/products/batch_exports/backend/presentation/views/batch_export/backfills.py
index b8a382a5b24c..9246c3b81a5b 100644
--- a/products/batch_exports/backend/presentation/views/batch_export/backfills.py
+++ b/products/batch_exports/backend/presentation/views/batch_export/backfills.py
@@ -1,18 +1,17 @@
"""Batch export backfill endpoints: create, list, retrieve and cancel."""
-import uuid
import dataclasses
from typing import Any
+from uuid import UUID
import structlog
import posthoganalytics
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
+from drf_spectacular.utils import extend_schema_field
from rest_framework import filters, mixins, request, response, serializers, status, viewsets
from rest_framework.exceptions import APIException, NotFound, ValidationError
from posthog.api.pagination import FacadeCursorPagination, facade_cursor_page_response
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.event_usage import groups
from posthog.models import User
@@ -23,20 +22,10 @@ from products.batch_exports.backend.facade import (
contracts,
)
from products.batch_exports.backend.facade.enums import BatchExportBackfillStatus
-from products.batch_exports.backend.presentation.views.utils import parse_path_uuid
logger = structlog.get_logger(__name__)
-# The viewset declares no queryset, so drf-spectacular cannot read the type of the ids from a model.
-BACKFILL_ID_PARAMETER = OpenApiParameter(
- "id",
- OpenApiTypes.UUID,
- OpenApiParameter.PATH,
- description="A UUID string identifying this batch export backfill.",
-)
-
-
class BatchExportBackfillSerializer(serializers.Serializer):
id = serializers.UUIDField(read_only=True)
progress = serializers.SerializerMethodField(read_only=True)
@@ -101,22 +90,16 @@ class TooManyConcurrentBackfills(APIException):
default_detail = "Too many concurrent batch export backfills for this team."
-@extend_schema(
- parameters=[
- OpenApiParameter(
- "batch_export_id",
- {"type": "string", "format": "uuid", "description": "The BatchExport this backfill belongs to."},
- OpenApiParameter.PATH,
- )
- ]
-)
-@extend_schema_view(retrieve=extend_schema(parameters=[BACKFILL_ID_PARAMETER]))
class BatchExportBackfillViewSet(TeamAndOrgViewSetMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
"""ViewSet for BatchExportBackfill models.
Allows creating and reading backfills, but not updating or deleting them.
"""
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this batch export backfill."),
+ "batch_export_id": PathParameter(type=UUID, description="The BatchExport this backfill belongs to."),
+ }
scope_object = "batch_export"
serializer_class = BatchExportBackfillSerializer
pagination_class = BackfillsCursorPagination
@@ -125,8 +108,8 @@ class BatchExportBackfillViewSet(TeamAndOrgViewSetMixin, mixins.RetrieveModelMix
ordering_fields = list(contracts.BATCH_EXPORT_BACKFILL_ORDERING_FIELDS)
ordering = "-created_at"
- def _get_export_id(self, detail: str | None = None) -> uuid.UUID:
- return parse_path_uuid(self.kwargs["parent_lookup_batch_export_id"], detail)
+ def _get_export_id(self) -> UUID:
+ return self.kwargs["parent_lookup_batch_export_id"]
def dangerously_get_object(self) -> contracts.BatchExportBackfillDetail:
# The mixin's get_object() reads through a queryset, which this view no longer has, so the
@@ -135,7 +118,7 @@ class BatchExportBackfillViewSet(TeamAndOrgViewSetMixin, mixins.RetrieveModelMix
# check_object_permissions runs on the contract.
try:
backfill = batch_exports_api.get_batch_export_backfill(
- self.team_id, self._get_export_id(), parse_path_uuid(self.kwargs["pk"])
+ self.team_id, self._get_export_id(), self.kwargs["pk"]
)
except contracts.BatchExportBackfillNotFoundError as e:
raise NotFound(*e.args) from e
@@ -151,7 +134,7 @@ class BatchExportBackfillViewSet(TeamAndOrgViewSetMixin, mixins.RetrieveModelMix
def create(self, request: request.Request, *args, **kwargs) -> response.Response:
"""Create a new backfill for a BatchExport."""
- export_id = self._get_export_id("BatchExport not found.")
+ export_id = self._get_export_id()
start_at = request.data.get("start_at")
end_at = request.data.get("end_at")
@@ -186,7 +169,6 @@ class BatchExportBackfillViewSet(TeamAndOrgViewSetMixin, mixins.RetrieveModelMix
return response.Response({"backfill_id": backfill.backfill_id}, status=status.HTTP_201_CREATED)
- @extend_schema(parameters=[BACKFILL_ID_PARAMETER])
@action(methods=["POST"], detail=True, required_scopes=["batch_export:write"])
def cancel(self, *args, **kwargs) -> response.Response:
"""Cancel a batch export backfill."""
diff --git a/products/batch_exports/backend/presentation/views/batch_export/exports.py b/products/batch_exports/backend/presentation/views/batch_export/exports.py
index 6567f8e45a0a..a048e176ba20 100644
--- a/products/batch_exports/backend/presentation/views/batch_export/exports.py
+++ b/products/batch_exports/backend/presentation/views/batch_export/exports.py
@@ -5,14 +5,13 @@ import typing
import dataclasses
import posthoganalytics
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view
+from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import request, response, serializers, status, viewsets
from rest_framework.exceptions import NotAuthenticated, NotFound, PermissionDenied, ValidationError
from posthog.api.log_entries import LogEntryMixin
from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.integrations import IntegrationRecord
from posthog.models import User
@@ -43,7 +42,6 @@ from products.batch_exports.backend.presentation.views.utils import (
HogQLModifiersField,
check_high_frequency_batch_exports_enabled,
check_hogql_batch_exports_enabled,
- parse_path_uuid,
)
from . import (
@@ -565,7 +563,7 @@ class BatchExportSerializer(serializers.Serializer):
export_id = self.instance.id
elif view is not None and "pk" in view.kwargs:
# Running validation for a `detail=True` action.
- export_id = uuid.UUID(str(view.kwargs["pk"]))
+ export_id = view.kwargs["pk"]
try:
batch_exports_api.validate_batch_export_destination(
@@ -652,12 +650,6 @@ class BatchExportSerializer(serializers.Serializer):
raise serializers.ValidationError(str(e))
-# The viewset has no queryset to type the `id` path parameter from, so each detail action declares it.
-BATCH_EXPORT_ID_PARAMETER = OpenApiParameter(
- "id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="A UUID string identifying this batch export."
-)
-
-
@extend_schema(tags=["batch_exports"])
@extend_schema_view(
# Request bodies use a polymorphic destination schema so that integration-backed types
@@ -666,13 +658,11 @@ BATCH_EXPORT_ID_PARAMETER = OpenApiParameter(
# created before integrations keep their inline credentials on update.
# Responses continue to use BatchExportSerializer.
create=extend_schema(request=BatchExportRequestSerializer),
- update=extend_schema(request=BatchExportRequestSerializer, parameters=[BATCH_EXPORT_ID_PARAMETER]),
- partial_update=extend_schema(request=BatchExportRequestSerializer, parameters=[BATCH_EXPORT_ID_PARAMETER]),
- retrieve=extend_schema(parameters=[BATCH_EXPORT_ID_PARAMETER]),
- destroy=extend_schema(parameters=[BATCH_EXPORT_ID_PARAMETER]),
- logs=extend_schema(parameters=[BATCH_EXPORT_ID_PARAMETER]),
+ update=extend_schema(request=BatchExportRequestSerializer),
+ partial_update=extend_schema(request=BatchExportRequestSerializer),
)
class BatchExportViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.ModelViewSet):
+ path_parameters = {"pk": PathParameter(type=uuid.UUID, description="A UUID string identifying this batch export.")}
scope_object = "batch_export"
serializer_class = BatchExportSerializer
pagination_class = FacadeLimitOffsetPagination
@@ -683,7 +673,7 @@ class BatchExportViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.ModelVi
# export is read through the facade instead. That skips the mixin's team filter and object
# permission check, so both happen here: the facade filters by team, and
# check_object_permissions runs on the contract. `logs` reads the export through here too.
- export_id = parse_path_uuid(self.kwargs["pk"])
+ export_id = self.kwargs["pk"]
try:
batch_export = batch_exports_api.get_batch_export(
self.team_id, export_id, include_latest_runs=self.action == "retrieve"
@@ -699,7 +689,7 @@ class BatchExportViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.ModelVi
lambda page: batch_exports_api.list_batch_exports(self.team_id, page=page),
)
- @extend_schema(request=None, parameters=[BATCH_EXPORT_ID_PARAMETER])
+ @extend_schema(request=None)
@action(methods=["POST"], detail=True, required_scopes=["batch_export:write"])
def pause(self, request: request.Request, *args, **kwargs) -> response.Response:
"""Pause a BatchExport."""
@@ -720,7 +710,7 @@ class BatchExportViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.ModelVi
return response.Response({"paused": True})
- @extend_schema(request=BatchExportUnpauseRequestSerializer, parameters=[BATCH_EXPORT_ID_PARAMETER])
+ @extend_schema(request=BatchExportUnpauseRequestSerializer)
@action(methods=["POST"], detail=True, required_scopes=["batch_export:write"])
def unpause(self, request: request.Request, *args, **kwargs) -> response.Response:
"""Unpause a BatchExport."""
@@ -807,7 +797,6 @@ class BatchExportViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.ModelVi
return self._run_destination_test_step(serializer, test_step, export_id=None)
- @extend_schema(parameters=[BATCH_EXPORT_ID_PARAMETER])
@action(methods=["POST"], detail=True, required_scopes=["batch_export:write"])
def run_test_step(self, request: request.Request, *args, **kwargs) -> response.Response:
test_step = self._parse_destination_test_step(request)
diff --git a/products/batch_exports/backend/presentation/views/batch_export/runs.py b/products/batch_exports/backend/presentation/views/batch_export/runs.py
index e0dbc9fbe074..67651020be91 100644
--- a/products/batch_exports/backend/presentation/views/batch_export/runs.py
+++ b/products/batch_exports/backend/presentation/views/batch_export/runs.py
@@ -1,18 +1,17 @@
"""Batch export run endpoints: list, retrieve, retry and cancel."""
-import uuid
from typing import Any, cast
+from uuid import UUID
from django.utils.timezone import now
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view
+from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import filters, mixins, request, response, serializers, status, viewsets
from rest_framework.exceptions import NotFound, ValidationError
from posthog.api.log_entries import LogEntryMixin
from posthog.api.pagination import FacadeCursorPagination, facade_cursor_page_response
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.models.integer_field_bounds import (
BIG_INTEGER_FIELD_MAX,
@@ -27,12 +26,6 @@ from products.batch_exports.backend.facade import (
contracts,
)
from products.batch_exports.backend.facade.enums import BatchExportRunStatus
-from products.batch_exports.backend.presentation.views.utils import parse_path_uuid
-
-# The viewset declares no queryset, so drf-spectacular cannot read the type of the ids from a model.
-RUN_ID_PARAMETER = OpenApiParameter(
- "id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="A UUID string identifying this batch export run."
-)
class BatchExportRunSerializer(serializers.Serializer):
@@ -164,22 +157,13 @@ class RunsCursorPagination(FacadeCursorPagination):
page_size = 100
-@extend_schema(
- tags=["batch_exports"],
- parameters=[
- OpenApiParameter(
- "batch_export_id",
- {"type": "string", "format": "uuid", "description": "The `BatchExport` this run belongs to."},
- OpenApiParameter.PATH,
- )
- ],
-)
-@extend_schema_view(
- list=extend_schema(parameters=[BatchExportRunListQuerySerializer]),
- retrieve=extend_schema(parameters=[RUN_ID_PARAMETER]),
- logs=extend_schema(parameters=[RUN_ID_PARAMETER]),
-)
+@extend_schema(tags=["batch_exports"])
+@extend_schema_view(list=extend_schema(parameters=[BatchExportRunListQuerySerializer]))
class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this batch export run."),
+ "batch_export_id": PathParameter(type=UUID, description="The `BatchExport` this run belongs to."),
+ }
scope_object = "batch_export"
serializer_class = BatchExportRunSerializer
pagination_class = RunsCursorPagination
@@ -192,8 +176,8 @@ class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, mixins.Retrie
def get_log_entry_instance_id(self) -> str:
return cast(str, self.parents_query_dict["run_id"])
- def _get_export_id(self) -> uuid.UUID:
- return parse_path_uuid(self.kwargs["parent_lookup_batch_export_id"])
+ def _get_export_id(self) -> UUID:
+ return self.kwargs["parent_lookup_batch_export_id"]
def _get_run_filters(self) -> contracts.BatchExportRunFilters:
query = BatchExportRunListQuerySerializer(data=self.request.GET)
@@ -228,9 +212,7 @@ class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, mixins.Retrie
# permission check, so both happen here: the facade filters by team and export, and
# check_object_permissions runs on the contract. `logs` reads the run through here too.
try:
- run = batch_exports_api.get_batch_export_run(
- self.team_id, self._get_export_id(), parse_path_uuid(self.kwargs["pk"])
- )
+ run = batch_exports_api.get_batch_export_run(self.team_id, self._get_export_id(), self.kwargs["pk"])
except contracts.BatchExportRunNotFoundError as e:
raise NotFound(*e.args) from e
self.check_object_permissions(self.request, run)
@@ -244,7 +226,6 @@ class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, mixins.Retrie
lambda page: batch_exports_api.list_batch_export_runs(self.team_id, export_id, filters=filters, page=page),
)
- @extend_schema(parameters=[RUN_ID_PARAMETER])
@action(methods=["POST"], detail=True, required_scopes=["batch_export:write"])
def retry(self, *args, **kwargs) -> response.Response:
"""Retry a batch export run.
@@ -261,7 +242,6 @@ class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, mixins.Retrie
return response.Response({"backfill_id": backfill_id}, status=status.HTTP_201_CREATED)
- @extend_schema(parameters=[RUN_ID_PARAMETER])
@action(methods=["POST"], detail=True, required_scopes=["batch_export:write"])
def cancel(self, *args, **kwargs) -> response.Response:
"""Cancel a batch export run."""
diff --git a/products/batch_exports/backend/presentation/views/file_download.py b/products/batch_exports/backend/presentation/views/file_download.py
index 2d3c2b10cb64..d548fbe98dbe 100644
--- a/products/batch_exports/backend/presentation/views/file_download.py
+++ b/products/batch_exports/backend/presentation/views/file_download.py
@@ -1,17 +1,11 @@
import datetime as dt
from typing import Any
+from uuid import UUID
from django.db import models
from django.http import HttpResponseRedirect
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import (
- OpenApiParameter,
- OpenApiResponse,
- PolymorphicProxySerializer,
- extend_schema,
- extend_schema_view,
-)
+from drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializer, extend_schema
from rest_framework import response, serializers, status, viewsets
from rest_framework.exceptions import APIException, NotAuthenticated, NotFound, ValidationError
from rest_framework.throttling import BaseThrottle
@@ -21,7 +15,7 @@ from posthog.hogql.errors import ExposedHogQLError
from posthog.api.log_entries import LogEntryMixin
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.errors import ExposedCHQueryError
from posthog.exceptions import ClickHouseQueryTimeOut
@@ -37,15 +31,10 @@ from products.batch_exports.backend.presentation.views.utils import (
HOGQL_MODIFIERS_HELP_TEXT,
HogQLModifiersField,
check_hogql_batch_exports_enabled,
- parse_path_uuid,
)
FILE_DOWNLOAD_MAX_RANGE = dt.timedelta(weeks=1)
DEFAULT_MAX_SIZE_MB = 1024
-# The viewset declares no queryset, so drf-spectacular cannot read the type of the id from a model.
-RUN_ID_PARAMETER = OpenApiParameter(
- "id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="A UUID string identifying this batch export run."
-)
class FileFormat(models.TextChoices):
@@ -378,8 +367,8 @@ def _to_file_download_request(validated_data: dict[str, Any]) -> contracts.FileD
@extend_schema(tags=["batch_exports"])
-@extend_schema_view(logs=extend_schema(parameters=[RUN_ID_PARAMETER]))
class FileDownloadBatchExportOnDemandViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.GenericViewSet):
+ path_parameters = {"pk": PathParameter(type=UUID, description="A UUID string identifying this batch export run.")}
scope_object = "batch_export"
serializer_class = FileDownloadBatchExportOnDemandSerializer
pagination_class = FacadeLimitOffsetPagination
@@ -403,7 +392,7 @@ class FileDownloadBatchExportOnDemandViewSet(TeamAndOrgViewSetMixin, LogEntryMix
# run is read through the facade instead. That skips the mixin's team filter and object
# permission check, so both happen here: the facade filters by team, and
# check_object_permissions runs on the contract. `logs` reads the run through here too.
- run_id = parse_path_uuid(self.kwargs["pk"])
+ run_id = self.kwargs["pk"]
try:
run = batch_exports_api.get_file_download_run(self.team_id, run_id)
except contracts.FileDownloadNotFoundError as e:
@@ -457,7 +446,6 @@ class FileDownloadBatchExportOnDemandViewSet(TeamAndOrgViewSetMixin, LogEntryMix
return response.Response({"id": run_id}, status=status.HTTP_202_ACCEPTED)
@extend_schema(
- parameters=[RUN_ID_PARAMETER],
responses={
200: PolymorphicProxySerializer(
component_name="RetrieveFileDownloadResponse",
@@ -494,7 +482,6 @@ class FileDownloadBatchExportOnDemandViewSet(TeamAndOrgViewSetMixin, LogEntryMix
return response.Response(body)
- @extend_schema(parameters=[RUN_ID_PARAMETER])
@action(
methods=["GET"], detail=True, url_path=r"download(?:/(?P<part>[^/.]+))?", required_scopes=["batch_export:read"]
)
@@ -523,7 +510,7 @@ class FileDownloadBatchExportOnDemandViewSet(TeamAndOrgViewSetMixin, LogEntryMix
return response
- @extend_schema(request=None, parameters=[RUN_ID_PARAMETER])
+ @extend_schema(request=None)
@action(methods=["POST"], detail=True, required_scopes=["batch_export:write"])
def cancel(self, request, *args, **kwargs) -> response.Response:
"""Cancel an ongoing file-download batch export."""
diff --git a/products/batch_exports/backend/presentation/views/utils.py b/products/batch_exports/backend/presentation/views/utils.py
index 23702babc9b9..9e11059cdb6e 100644
--- a/products/batch_exports/backend/presentation/views/utils.py
+++ b/products/batch_exports/backend/presentation/views/utils.py
@@ -1,11 +1,10 @@
-import uuid
import typing
import pydantic
import posthoganalytics
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
-from rest_framework.exceptions import NotFound, PermissionDenied
+from rest_framework.exceptions import PermissionDenied
from posthog.schema import HogQLQueryModifiers
@@ -23,16 +22,6 @@ HOGQL_MODIFIERS_HELP_TEXT = (
)
-# TODO: Nothing here is specific to batch exports. Move it to posthog/api/utils.py and replace the
-# copies in cross_project_dashboards, review_hog, visual_review and the web_analytics heatmaps views.
-def parse_path_uuid(value: object, detail: str | None = None) -> uuid.UUID:
- """Return a UUID path parameter. A value that is not a UUID cannot name anything, so it is a 404."""
- try:
- return uuid.UUID(str(value))
- except ValueError:
- raise NotFound(detail)
-
-
def check_hogql_batch_exports_enabled(team: Team) -> None:
"""Raise if HogQL-powered batch exports are not enabled for the team."""
if not posthoganalytics.feature_enabled(
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.py
index 800f43afd3f5..b8c25bb13c8a 100644
--- a/products/canvas/backend/presentation/views.py
+++ b/products/canvas/backend/presentation/views.py
@@ -21,7 +21,7 @@ from rest_framework.throttling import BaseThrottle, SimpleRateThrottle
from rest_framework.utils.urls import replace_query_param
from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication
from posthog.event_usage import report_user_action
from posthog.helpers.impersonation import is_impersonated
@@ -371,6 +371,10 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
scope_object = "canvas"
# The facade reads canvases; the viewset holds no queryset.
queryset = None
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this canvas."),
+ "root_comment_id": UUID,
+ }
serializer_class = CanvasSerializer
pagination_class = FacadeLimitOffsetPagination
http_method_names = ["get", "post", "patch", "delete", "head", "options"]
@@ -764,10 +768,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
@extend_schema(
operation_id="canvases_comments_retrieve",
- parameters=[
- OpenApiParameter("root_comment_id", UUID, OpenApiParameter.PATH),
- CanvasCommentDetailQuerySerializer,
- ],
+ parameters=[CanvasCommentDetailQuerySerializer],
responses=CanvasCommentDetailSerializer,
)
@action(
@@ -776,21 +777,17 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
url_path=r"comments/(?P<root_comment_id>[^/.]+)",
required_scopes=["canvas:read", "comment:read"],
)
- def comment(self, request: Request, *args: Any, root_comment_id: str | None = None, **kwargs: Any) -> Response:
+ def comment(self, request: Request, *args: Any, root_comment_id: UUID, **kwargs: Any) -> Response:
"""One comment thread on this canvas: the root comment and its replies, oldest first."""
params = CanvasCommentDetailQuerySerializer(data=request.query_params)
params.is_valid(raise_exception=True)
canvas = self._canvas()
- try:
- parsed_comment_id = UUID(str(root_comment_id))
- except ValueError:
- raise NotFound()
try:
thread = tasks_facade.retrieve_canvas_comment(
team_id=self.team_id,
canvas_id=canvas.id,
canvas_name=canvas.name,
- comment_id=parsed_comment_id,
+ comment_id=root_comment_id,
limit=params.validated_data["limit"],
cursor=params.validated_data.get("cursor"),
content_comment_id=params.validated_data.get("comment_id"),
@@ -2197,20 +2194,3 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
canvas_name=canvas.name or "Canvas",
canvas_url=canvas_url(canvas),
)
-
-
-# The viewset holds no model, so drf-spectacular cannot type the id path parameter by itself.
-_CANVAS_ID_PARAMETER = OpenApiParameter(
- "id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="A UUID string identifying this canvas."
-)
-for _detail_action in [
- "retrieve",
- "partial_update",
- "destroy",
- *(extra.__name__ for extra in CanvasViewSet.get_extra_actions() if getattr(extra, "detail", False)),
-]:
- setattr(
- CanvasViewSet,
- _detail_action,
- extend_schema(parameters=[_CANVAS_ID_PARAMETER])(getattr(CanvasViewSet, _detail_action)),
- )
diff --git a/products/cross_project_dashboards/backend/presentation/views.py b/products/cross_project_dashboards/backend/presentation/views.py
index 248a369dae52..ce3041369142 100644
--- a/products/cross_project_dashboards/backend/presentation/views.py
+++ b/products/cross_project_dashboards/backend/presentation/views.py
@@ -3,8 +3,7 @@
from typing import Any, cast
from uuid import UUID
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter, extend_schema
+from drf_spectacular.utils import extend_schema
from rest_framework import status, viewsets
from rest_framework.exceptions import NotFound, PermissionDenied
from rest_framework.permissions import BasePermission
@@ -12,7 +11,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.models import User
from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids
@@ -25,18 +24,7 @@ from .serializers import (
)
CHANGE_DENIED = "This dashboard has tiles from a project you cannot open, so you cannot change or delete it."
-DASHBOARD_ID = OpenApiParameter("id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Id of the dashboard.")
-PARENT_DASHBOARD_ID = OpenApiParameter(
- "dashboard_id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Id of the dashboard."
-)
-TILE_ID = OpenApiParameter("id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Id of the tile.")
-
-
-def _uuid(value: str) -> UUID:
- try:
- return UUID(value)
- except ValueError:
- raise NotFound()
+DASHBOARD_ID = PathParameter(type=UUID, description="Id of the dashboard.")
class CrossProjectDashboardPagination(FacadeLimitOffsetPagination):
@@ -66,6 +54,7 @@ class CrossProjectDashboardViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
scope_object = "cross_project_dashboard"
serializer_class = CrossProjectDashboardSerializer
lookup_field = "id"
+ path_parameters = {"id": DASHBOARD_ID}
pagination_class = CrossProjectDashboardPagination
# Server-side rollout boundary: the flag gates the API, not only the UI.
posthog_feature_flag = "cross-project-dashboards"
@@ -75,7 +64,7 @@ class CrossProjectDashboardViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
return cast(User, self.request.user)
def _object_id(self) -> UUID:
- return _uuid(self.kwargs["id"])
+ return self.kwargs["id"]
@extend_schema(responses={200: CrossProjectDashboardListItemSerializer(many=True)})
def list(self, request: Request, **kwargs: Any) -> Response:
@@ -96,7 +85,7 @@ class CrossProjectDashboardViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
)
return Response(CrossProjectDashboardSerializer(dashboard).data, status=status.HTTP_201_CREATED)
- @extend_schema(parameters=[DASHBOARD_ID], responses={200: CrossProjectDashboardSerializer})
+ @extend_schema(responses={200: CrossProjectDashboardSerializer})
def retrieve(self, request: Request, **kwargs: Any) -> Response:
try:
dashboard = api.get_dashboard(
@@ -107,7 +96,6 @@ class CrossProjectDashboardViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
return Response(CrossProjectDashboardSerializer(dashboard).data)
@extend_schema(
- parameters=[DASHBOARD_ID],
request=CrossProjectDashboardSerializer(partial=True),
responses={200: CrossProjectDashboardSerializer},
)
@@ -125,7 +113,7 @@ class CrossProjectDashboardViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
raise PermissionDenied(CHANGE_DENIED)
return Response(CrossProjectDashboardSerializer(dashboard).data)
- @extend_schema(parameters=[DASHBOARD_ID], responses={204: None})
+ @extend_schema(responses={204: None})
def destroy(self, request: Request, **kwargs: Any) -> Response:
try:
api.delete_dashboard(
@@ -148,6 +136,10 @@ class CrossProjectDashboardTileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericV
scope_object = "cross_project_dashboard"
serializer_class = CrossProjectDashboardTileSerializer
lookup_field = "id"
+ path_parameters = {
+ "id": PathParameter(type=UUID, description="Id of the tile."),
+ "dashboard_id": DASHBOARD_ID,
+ }
pagination_class = CrossProjectDashboardPagination
posthog_feature_flag = "cross-project-dashboards"
permission_classes = [PostHogFeatureFlagPermission, OrganizationWideCredentialPermission]
@@ -156,12 +148,12 @@ class CrossProjectDashboardTileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericV
return cast(User, self.request.user)
def _object_id(self) -> UUID:
- return _uuid(self.kwargs["id"])
+ return self.kwargs["id"]
def _dashboard_id(self) -> UUID:
- return _uuid(self.parents_query_dict["dashboard_id"])
+ return self.kwargs["parent_lookup_dashboard_id"]
- @extend_schema(parameters=[PARENT_DASHBOARD_ID], responses={200: CrossProjectDashboardTileSerializer(many=True)})
+ @extend_schema(responses={200: CrossProjectDashboardTileSerializer(many=True)})
def list(self, request: Request, **kwargs: Any) -> Response:
return facade_page_response(
self,
@@ -171,7 +163,6 @@ class CrossProjectDashboardTileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericV
)
@extend_schema(
- parameters=[PARENT_DASHBOARD_ID],
request=CrossProjectDashboardTileSerializer,
responses={201: CrossProjectDashboardTileSerializer},
)
@@ -191,7 +182,7 @@ class CrossProjectDashboardTileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericV
raise PermissionDenied(CHANGE_DENIED)
return Response(CrossProjectDashboardTileSerializer(tile).data, status=status.HTTP_201_CREATED)
- @extend_schema(parameters=[PARENT_DASHBOARD_ID, TILE_ID], responses={200: CrossProjectDashboardTileSerializer})
+ @extend_schema(responses={200: CrossProjectDashboardTileSerializer})
def retrieve(self, request: Request, **kwargs: Any) -> Response:
try:
tile = api.get_tile(
@@ -205,7 +196,6 @@ class CrossProjectDashboardTileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericV
return Response(CrossProjectDashboardTileSerializer(tile).data)
@extend_schema(
- parameters=[PARENT_DASHBOARD_ID, TILE_ID],
request=CrossProjectDashboardTileUpdateSerializer(partial=True),
responses={200: CrossProjectDashboardTileSerializer},
)
@@ -227,7 +217,7 @@ class CrossProjectDashboardTileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericV
raise PermissionDenied(CHANGE_DENIED)
return Response(CrossProjectDashboardTileSerializer(tile).data)
- @extend_schema(parameters=[PARENT_DASHBOARD_ID, TILE_ID], responses={204: None})
+ @extend_schema(responses={204: None})
def destroy(self, request: Request, **kwargs: Any) -> Response:
try:
api.delete_tile(
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 3cf82d58e6a3..cbf7cb415c29 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -38,7 +38,7 @@ from rest_framework.throttling import UserRateThrottle
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.api.tagged_item import TaggedItemViewSetMixin
from posthog.auth import SessionAuthentication, is_mcp_request
from posthog.event_usage import report_user_action
@@ -196,16 +196,7 @@ def _warehouse_scoped_uac(view: Any) -> UserAccessControl:
return cast(UserAccessControl, _ScopeGatedAccessControl(view.user_access_control, scopes))
-# drf-spectacular auto-describes the pk path param for a model-backed viewset as
-# "A UUID string identifying this <model>.". These viewsets reach the model through the
-# facade (no ``queryset``), so the description is declared explicitly to keep the generated
-# OpenAPI (and MCP) path params byte-identical.
-_ACCOUNT_ID_PARAM = OpenApiParameter(
- "id",
- OpenApiTypes.STR,
- OpenApiParameter.PATH,
- description="A UUID string identifying this account.",
-)
+_PARENT_ACCOUNT_ID = PathParameter(type=UUID, description="UUID of the parent account.")
# NOTE: deliberately no class docstring — a docstring here is inherited as the ViewSets'
@@ -1948,6 +1939,14 @@ class AccountViewSet(
scope_object = "account"
serializer_class = AccountSerializer
queryset = None
+ # drf-spectacular describes a model-backed pk as "A UUID string identifying this <model>.", and this
+ # viewset has no queryset, so the description is spelled out. The facade takes the id as a string and
+ # answers not found for a malformed one, so it stays `str` here.
+ path_parameters = {
+ "pk": PathParameter(type=str, description="A UUID string identifying this account."),
+ "ticket_id": UUID,
+ "thread_id": UUID,
+ }
pagination_class = FacadeLimitOffsetPagination
bulk_update_tags = None # Mixin action assumes integer PKs; Account uses UUIDs.
@@ -2042,7 +2041,6 @@ class AccountViewSet(
serializer_class=AccountSerializer,
)
- @extend_schema(parameters=[_ACCOUNT_ID_PARAM])
def retrieve(self, request: Request, *args, **kwargs) -> Response:
try:
account = api.get_account_for_view(
@@ -2083,7 +2081,6 @@ class AccountViewSet(
return Response(AccountSerializer(instance=account).data)
@extend_schema(
- parameters=[_ACCOUNT_ID_PARAM],
request=None,
responses={200: AccountPresenceViewerSerializer(many=True)},
)
@@ -2125,7 +2122,7 @@ class AccountViewSet(
)
return Response(AccountPresenceSerializer(instance=presence, many=True).data)
- @extend_schema(parameters=[_ACCOUNT_ID_PARAM], responses={200: SupportTicketSerializer(many=True)})
+ @extend_schema(responses={200: SupportTicketSerializer(many=True)})
@action(methods=["GET"], detail=True, pagination_class=None)
def support_tickets(self, request: Request, *args, **kwargs) -> Response:
try:
@@ -2142,7 +2139,6 @@ class AccountViewSet(
@extend_schema(
operation_id="accounts_support_ticket_messages_list",
- parameters=[_ACCOUNT_ID_PARAM],
responses={200: SupportTicketMessageSerializer(many=True)},
)
@action(
@@ -2152,16 +2148,11 @@ class AccountViewSet(
url_name="support-ticket-detail",
pagination_class=AccountEmailThreadMessagePagination,
)
- def support_ticket(self, request: Request, ticket_id: str, *args, **kwargs) -> Response:
- try:
- parsed_ticket_id = str(UUID(ticket_id))
- except ValueError:
- return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
-
+ def support_ticket(self, request: Request, ticket_id: UUID, *args, **kwargs) -> Response:
def fetch(page: PageRequest) -> Page[api.SupportTicketMessage]:
try:
result = api.get_account_support_ticket_messages(
- self.team_id, self.kwargs["pk"], parsed_ticket_id, self.user_access_control, page=page
+ self.team_id, self.kwargs["pk"], str(ticket_id), self.user_access_control, page=page
)
except api.ResourceForbiddenError:
raise PermissionDenied()
@@ -2171,7 +2162,7 @@ class AccountViewSet(
return facade_page_response(self, fetch, serializer_class=SupportTicketMessageSerializer)
- @extend_schema(parameters=[_ACCOUNT_ID_PARAM], responses={200: AccountEmailThreadSerializer(many=True)})
+ @extend_schema(responses={200: AccountEmailThreadSerializer(many=True)})
@action(methods=["GET"], detail=True, url_path="email_threads")
def email_threads(self, request: Request, *args, **kwargs) -> Response:
if api.get_accessible_account_id(self.team_id, self.kwargs["pk"], self.user_access_control) is None:
@@ -2192,7 +2183,6 @@ class AccountViewSet(
@extend_schema(
operation_id="accounts_email_thread_messages_list",
- parameters=[_ACCOUNT_ID_PARAM],
responses={200: AccountEmailThreadMessageSerializer(many=True)},
)
@action(
@@ -2202,16 +2192,11 @@ class AccountViewSet(
url_name="email-thread-detail",
pagination_class=AccountEmailThreadMessagePagination,
)
- def email_thread(self, request: Request, thread_id: str, *args, **kwargs) -> Response:
- try:
- parsed_thread_id = str(UUID(thread_id))
- except ValueError:
- return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
-
+ def email_thread(self, request: Request, thread_id: UUID, *args, **kwargs) -> Response:
def fetch(page: PageRequest) -> Page[api.AccountEmailThreadMessage]:
try:
result = api.get_account_email_thread_messages(
- self.team_id, self.kwargs["pk"], parsed_thread_id, self.user_access_control, page=page
+ self.team_id, self.kwargs["pk"], str(thread_id), self.user_access_control, page=page
)
except api.ResourceForbiddenError:
raise PermissionDenied()
@@ -2223,7 +2208,6 @@ class AccountViewSet(
@extend_schema(
parameters=[
- _ACCOUNT_ID_PARAM,
OpenApiParameter(
name="search",
type=OpenApiTypes.STR,
@@ -2306,7 +2290,6 @@ class AccountViewSet(
raise Conflict(str(e))
return Response(AccountSerializer(instance=account).data, status=status.HTTP_201_CREATED)
- @extend_schema(parameters=[_ACCOUNT_ID_PARAM])
def update(self, request: Request, *args, **kwargs) -> Response:
partial = kwargs.pop("partial", False)
serializer = AccountSerializer(data=request.data, partial=partial)
@@ -2351,12 +2334,11 @@ class AccountViewSet(
raise Conflict(str(e))
return Response(AccountSerializer(instance=account).data)
- @extend_schema(parameters=[_ACCOUNT_ID_PARAM])
def partial_update(self, request: Request, *args, **kwargs) -> Response:
kwargs["partial"] = True
return self.update(request, *args, **kwargs)
- @extend_schema(parameters=[_ACCOUNT_ID_PARAM], responses={200: AccountChannelSummarySerializer(many=True)})
+ @extend_schema(responses={200: AccountChannelSummarySerializer(many=True)})
@action(methods=["GET"], detail=True)
def summaries(self, request: Request, *args, **kwargs) -> Response:
if api.get_accessible_account_id(self.team_id, self.kwargs["pk"], self.user_access_control) is None:
@@ -2372,7 +2354,6 @@ class AccountViewSet(
return facade_page_response(self, fetch, serializer_class=AccountChannelSummarySerializer)
- @extend_schema(parameters=[_ACCOUNT_ID_PARAM])
def destroy(self, request: Request, *args, **kwargs) -> Response:
try:
api.delete_account_for_view(
@@ -2402,17 +2383,7 @@ def _account_tags_input(serializer) -> list[str] | None:
return serializer.initial_data.get("tags")
-@extend_schema(
- tags=["customer_analytics"],
- parameters=[
- OpenApiParameter(
- name="account_id",
- type=OpenApiTypes.UUID,
- location=OpenApiParameter.PATH,
- description="UUID of the parent account.",
- ),
- ],
-)
+@extend_schema(tags=["customer_analytics"])
class AccountNotebookViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
@@ -2424,6 +2395,7 @@ class AccountNotebookViewSet(
):
scope_object = "account"
serializer_class = AccountNotebookSerializer
+ path_parameters = {"account_id": _PARENT_ACCOUNT_ID}
queryset = None
lookup_field = "short_id"
@@ -2620,20 +2592,11 @@ class AccountNotesViewSet(
)
-@extend_schema(
- tags=["customer_analytics"],
- parameters=[
- OpenApiParameter(
- name="account_id",
- type=OpenApiTypes.UUID,
- location=OpenApiParameter.PATH,
- description="UUID of the parent account.",
- ),
- ],
-)
+@extend_schema(tags=["customer_analytics"])
class CustomPropertyValueViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.GenericViewSet):
scope_object = "account"
serializer_class = CustomPropertyValueSerializer
+ path_parameters = {"account_id": _PARENT_ACCOUNT_ID}
pagination_class = None
def _accessible_account_id(self) -> str | None:
@@ -2704,20 +2667,11 @@ _AGENT_ROLE_MANAGED = (
)
-@extend_schema(
- tags=["customer_analytics"],
- parameters=[
- OpenApiParameter(
- name="account_id",
- type=OpenApiTypes.UUID,
- location=OpenApiParameter.PATH,
- description="UUID of the parent account.",
- ),
- ],
-)
+@extend_schema(tags=["customer_analytics"])
class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.GenericViewSet):
scope_object = "account"
serializer_class = AccountRelationshipSerializer
+ path_parameters = {"account_id": _PARENT_ACCOUNT_ID}
permission_classes = [AccountRelationshipDeletePermission]
pagination_class = None
@@ -2817,14 +2771,6 @@ class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
return Response(status=status.HTTP_204_NO_CONTENT)
-_EVENT_STREAM_ID_PARAM = OpenApiParameter(
- "id",
- OpenApiTypes.STR,
- OpenApiParameter.PATH,
- description="A UUID string identifying this event stream.",
-)
-
-
class EventStreamTestMessageThrottle(UserRateThrottle):
"""Each test message posts to Slack, so cap the rate per user regardless of auth method."""
@@ -2850,6 +2796,7 @@ class EventStreamViewSet(
scope_object = "account"
serializer_class = EventStreamSerializer
+ path_parameters = {"pk": PathParameter(type=str, description="A UUID string identifying this event stream.")}
pagination_class = None # at most one stream exists per team (one-to-one) — nothing to paginate
queryset = None # data is reached through the facade; declared for router/schema only
@@ -2880,7 +2827,6 @@ class EventStreamViewSet(
raise Conflict(str(e))
return Response(EventStreamSerializer(instance=stream).data, status=status.HTTP_201_CREATED)
- @extend_schema(parameters=[_EVENT_STREAM_ID_PARAM])
def update(self, request: Request, *args, **kwargs) -> Response:
partial = kwargs.pop("partial", False)
serializer = EventStreamSerializer(data=request.data, partial=partial)
@@ -2901,12 +2847,10 @@ class EventStreamViewSet(
raise ValidationError(str(e))
return Response(EventStreamSerializer(instance=stream).data)
- @extend_schema(parameters=[_EVENT_STREAM_ID_PARAM])
def partial_update(self, request: Request, *args, **kwargs) -> Response:
kwargs["partial"] = True
return self.update(request, *args, **kwargs)
- @extend_schema(parameters=[_EVENT_STREAM_ID_PARAM])
def destroy(self, request: Request, *args, **kwargs) -> Response:
deleted = api.delete_event_stream(
team_id=self.team_id, stream_id=self.kwargs["pk"], user=cast(User, request.user)
@@ -2916,7 +2860,6 @@ class EventStreamViewSet(
return Response(status=status.HTTP_204_NO_CONTENT)
@extend_schema(
- parameters=[_EVENT_STREAM_ID_PARAM],
request=EventStreamMemberWriteSerializer,
responses={200: EventStreamSerializer},
)
@@ -2925,7 +2868,6 @@ class EventStreamViewSet(
return self._set_member(request, included=True)
@extend_schema(
- parameters=[_EVENT_STREAM_ID_PARAM],
request=EventStreamMemberWriteSerializer,
responses={200: EventStreamSerializer},
)
@@ -2934,7 +2876,6 @@ class EventStreamViewSet(
return self._set_member(request, included=False)
@extend_schema(
- parameters=[_EVENT_STREAM_ID_PARAM],
request=None,
responses={200: EventStreamTestMessageSerializer},
)
diff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.py
index bc7e8531b8cc..f43ff8aa7c80 100644
--- a/products/visual_review/backend/presentation/views.py
+++ b/products/visual_review/backend/presentation/views.py
@@ -26,7 +26,7 @@ from rest_framework.response import Response
from posthog.api.mixins import TypedRequest, validated_request
from posthog.api.pagination import FacadeLimitOffsetPagination, PrecountedLimitOffsetPagination, facade_page_response
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.auth import is_mcp_request
from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH
@@ -87,19 +87,6 @@ def _actor(request: Request) -> ActorType:
return ActorType.AGENT if is_mcp_request(request) else ActorType.HUMAN
-def _parse_uuid(value: str, field: str) -> UUID:
- """Parse a parent lookup UUID, returning a 400 instead of letting a malformed value raise a 500.
-
- `path_parameters` parses only the view's own URL kwargs, so a parent segment such as the repo
- id in `repos/<repo_id>/runs/` reaches the viewset as a raw string. A malformed one (truncated,
- hallucinated by an MCP client, hand-typed) would otherwise crash `UUID(...)` with an
- uncaught `ValueError`. Convert that into a clean DRF validation error."""
- try:
- return UUID(value)
- except ValueError:
- raise ValidationError({field: "Must be a valid UUID."})
-
-
REVIEW_STATE_PARAMETER = OpenApiParameter(
"review_state",
str,
@@ -496,6 +483,7 @@ class SnapshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
scope_object = "visual_review"
+ path_parameters = {"repo_id": UUID}
scope_object_read_actions = ["timeline"]
@extend_schema(
@@ -517,7 +505,7 @@ class SnapshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
def timeline(self, request: Request, run_type: str, identifier: str, **kwargs) -> Response:
"""Deduped baseline timeline for a snapshot identity. Newest first."""
- repo_id = _parse_uuid(self.parents_query_dict["repo_id"], field="repo_id")
+ repo_id: UUID = self.kwargs["parent_lookup_repo_id"]
try:
api.get_repo(repo_id, team_id=self.team_id)
except api.RepoNotFoundError:
@@ -538,6 +526,8 @@ class RepoRunsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
scope_object = "visual_review"
+ path_parameters = {"repo_id": UUID}
+
pagination_class = FacadeLimitOffsetPagination
scope_object_read_actions = ["list", "counts"]
serializer_class = RunSerializer
@@ -563,7 +553,7 @@ class RepoRunsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
{"detail": f"search must be at most {MAX_SEARCH_LENGTH} characters"},
status=status.HTTP_400_BAD_REQUEST,
)
- repo_id = _parse_uuid(self.parents_query_dict["repo_id"], field="repo_id")
+ repo_id: UUID = self.kwargs["parent_lookup_repo_id"]
return facade_page_response(
self,
lambda page: api.list_runs(
@@ -576,7 +566,7 @@ class RepoRunsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@action(detail=False, methods=["get"])
def counts(self, request: Request, **kwargs) -> Response:
"""Review state counts for runs in this repo."""
- repo_id = _parse_uuid(self.parents_query_dict["repo_id"], field="repo_id")
+ repo_id: UUID = self.kwargs["parent_lookup_repo_id"]
return Response(api.get_review_state_counts(self.team_id, repo_id=repo_id))
@@ -588,7 +578,12 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
scope_object = "visual_review"
- path_parameters = {"pk": UUID, "request_id": UUID}
+ path_parameters = {
+ "pk": UUID,
+ "request_id": PathParameter(
+ type=UUID, description="UUID of a pending lift request for this run's pull request."
+ ),
+ }
pagination_class = FacadeLimitOffsetPagination
scope_object_write_actions = [
@@ -972,14 +967,6 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(QuarantineLiftEntrySerializer(instance=entries, many=True).data)
@extend_schema(
- parameters=[
- OpenApiParameter(
- "request_id",
- OpenApiTypes.UUID,
- OpenApiParameter.PATH,
- description="UUID of a pending lift request for this run's pull request.",
- ),
- ],
request=None,
responses={204: None},
description="Withdraw a pending request to lift a quarantine when this run's pull request merges.",
diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.py
index 64d0da75ef3a..44d26dc7dde8 100644
--- a/products/visual_review/backend/tests/test_presentation.py
+++ b/products/visual_review/backend/tests/test_presentation.py
@@ -1063,11 +1063,11 @@ class TestMalformedUuid(VisualReviewTeamScopedTestMixin, APIBaseTest):
("repo_retrieve", "get", "repos/{bad}/", status.HTTP_404_NOT_FOUND),
# A second path capture, declared in path_parameters next to pk.
("cancel_lift", "post", "runs/{run}/quarantine_lifts/{bad}/cancel/", status.HTTP_404_NOT_FOUND),
- # Parent path segment (parents_query_dict), which path_parameters does not parse.
- ("repo_nested_runs", "get", "repos/{bad}/runs/", status.HTTP_400_BAD_REQUEST),
+ # A parent path segment, declared in path_parameters by its bare name.
+ ("repo_nested_runs", "get", "repos/{bad}/runs/", status.HTTP_404_NOT_FOUND),
]
)
- def test_malformed_uuid_is_not_a_500(self, _name: str, method: str, path: str, expected_status: int) -> None:
+ def test_malformed_uuid_is_a_404(self, _name: str, method: str, path: str, expected_status: int) -> None:
suffix = path.format(bad=self.BAD_UUID, run=self.RUN_ID)
response = getattr(self.client, method)(f"/api/projects/{self.team.id}/visual_review/{suffix}")
diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.py
index 87c7997fea91..77b9844916e0 100644
--- a/products/web_analytics/backend/api/heatmaps_api.py
+++ b/products/web_analytics/backend/api/heatmaps_api.py
@@ -42,7 +42,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.mixins import ValidatedRequest, validated_request
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.uploaded_media import validate_image_file
from posthog.api.utils import action
@@ -1770,6 +1770,12 @@ class SavedHeatmapViewSet(
serializer_class = HeatmapScreenshotResponseSerializer
queryset = SavedHeatmap.objects.all()
lookup_field = "short_id"
+ path_parameters = {
+ "request_id": UUID,
+ "history_id": PathParameter(
+ type=UUID, description="ID of the capture, as listed by the screenshot history endpoint."
+ ),
+ }
# list() returns its own {results, count} shape (paginated via the query serializer), so
# opt out of the project-global LimitOffsetPagination to avoid a double-wrapped schema.
pagination_class = None
@@ -2100,13 +2106,6 @@ class SavedHeatmapViewSet(
raise NotFound()
return obj
- @staticmethod
- def _path_uuid(kwargs: dict[str, Any], name: str) -> UUID:
- try:
- return UUID(str(kwargs.get(name)))
- except ValueError:
- raise NotFound()
-
@extend_schema(
responses={
200: HeatmapScreenshotHistoryResponseSerializer,
@@ -2177,7 +2176,6 @@ class SavedHeatmapViewSet(
return response.Response(serializer.data, status=status.HTTP_202_ACCEPTED)
@extend_schema(
- parameters=[OpenApiParameter("request_id", OpenApiTypes.UUID, OpenApiParameter.PATH)],
responses={200: HeatmapCaptureRequestSerializer},
description="Read the outcome of a capture request.",
)
@@ -2189,7 +2187,7 @@ class SavedHeatmapViewSet(
)
def screenshot_history_request(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
obj = self._page_history_heatmap()
- request_id = self._path_uuid(kwargs, "request_id")
+ request_id: UUID = kwargs["request_id"]
capture = (
HeatmapCaptureRequest.objects.for_team(self.team.id)
.filter(heatmap=obj, id=request_id, expires_at__gt=timezone.now())
@@ -2200,15 +2198,7 @@ class SavedHeatmapViewSet(
return response.Response(HeatmapCaptureRequestSerializer(capture).data)
@extend_schema(
- parameters=[
- OpenApiParameter(
- name="history_id",
- type=OpenApiTypes.UUID,
- location=OpenApiParameter.PATH,
- description="ID of the capture, as listed by the screenshot history endpoint.",
- ),
- HeatmapScreenshotHistoryContentQuerySerializer,
- ],
+ parameters=[HeatmapScreenshotHistoryContentQuerySerializer],
responses={
(200, "image/jpeg"): OpenApiTypes.BINARY,
304: OpenApiResponse(description="Not modified"),
@@ -2228,7 +2218,7 @@ class SavedHeatmapViewSet(
obj = self._page_history_heatmap()
query = HeatmapScreenshotHistoryContentQuerySerializer(data=request.query_params)
query.is_valid(raise_exception=True)
- history_id = self._path_uuid(kwargs, "history_id")
+ history_id: UUID = kwargs["history_id"]
revision: UUID = query.validated_data["v"]
variant = query.validated_data["variant"]
now = timezone.now()