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.

fix(endpoints): mark variables without defaults as required in OpenAPI spec (#61836)

Jaydeep pipaliya83dd417bf9c9
diff --git a/products/endpoints/backend/openapi.py b/products/endpoints/backend/openapi.py
index f302c13d809e..6ab0d0ff3a26 100644
--- a/products/endpoints/backend/openapi.py
+++ b/products/endpoints/backend/openapi.py
@@ -31,6 +31,15 @@ def generate_openapi_spec(
target_version = version or endpoint.get_version()
description = target_version.description
+ schemas = _build_component_schemas(endpoint, target_version, team_id)
+ variables_required = bool(schemas.get("Variables", {}).get("required"))
+ if variables_required:
+ # The Variables schema's `required` array only fires once the caller
+ # actually includes a `variables` key. Make `variables` itself
+ # required on EndpointRunRequest too, otherwise an SDK client that
+ # POSTs `{}` passes validation.
+ schemas["EndpointRunRequest"].setdefault("required", []).append("variables")
+
return {
"openapi": "3.0.3",
"info": {
@@ -47,7 +56,7 @@ def generate_openapi_spec(
"description": description or f"Execute the {endpoint.name} endpoint",
"security": [{"PersonalAPIKey": []}],
"requestBody": {
- "required": False,
+ "required": variables_required,
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/EndpointRunRequest"},
@@ -113,7 +122,7 @@ def generate_openapi_spec(
"description": "Personal API Key from PostHog. Get one at /settings/user-api-keys",
}
},
- "schemas": _build_component_schemas(endpoint, target_version, team_id),
+ "schemas": schemas,
},
}
@@ -278,9 +287,9 @@ def _build_variables_schema(query: dict, is_materialized: bool, team_id: int) ->
"""Build schema for variables based on query type and materialization state."""
query_kind = query.get("kind")
properties: dict = {}
+ required: list[str] = []
if query_kind == "HogQLQuery":
- # HogQL: variables from query definition, with types from InsightVariable model
variables = query.get("variables", {})
if variables:
variable_ids = list(variables.keys())
@@ -306,6 +315,8 @@ def _build_variables_schema(query: dict, is_materialized: bool, team_id: int) ->
}
if default_value is not None:
properties[code_name]["example"] = default_value
+ else:
+ required.append(code_name)
else:
# Insight queries - only include breakdown for supported query types
if query_kind in InsightEndpointStrategy.BREAKDOWN_SUPPORTED_QUERY_TYPES:
@@ -317,9 +328,13 @@ def _build_variables_schema(query: dict, is_materialized: bool, team_id: int) ->
"description": f"Filter by {breakdown} breakdown value",
"example": "Chrome",
}
+ # Materialized insights resolve the breakdown column at materialization
+ # time, so callers have to supply the value at execution; non-materialized
+ # insights can fall back to the saved filter.
+ if is_materialized:
+ required.append(breakdown)
if not is_materialized:
- # Non-materialized also supports date variables
properties["date_from"] = {
"type": "string",
"description": "Filter results from this date (ISO format or relative like '-7d')",
@@ -334,9 +349,12 @@ def _build_variables_schema(query: dict, is_materialized: bool, team_id: int) ->
if not properties:
return None
- return {
+ schema: dict = {
"type": "object",
"description": "Query variables. For HogQL: code_names from query. For insights: breakdown property and date_from/date_to.",
"properties": properties,
"additionalProperties": False,
}
+ if required:
+ schema["required"] = required
+ return schema
diff --git a/products/endpoints/backend/tests/test_openapi_spec.py b/products/endpoints/backend/tests/test_openapi_spec.py
index cd933b010201..0fcde080554b 100644
--- a/products/endpoints/backend/tests/test_openapi_spec.py
+++ b/products/endpoints/backend/tests/test_openapi_spec.py
@@ -91,6 +91,125 @@ class TestEndpointOpenAPISpec(ClickhouseTestMixin, APIBaseTest):
self.assertIn("country", variables_schema["properties"])
self.assertEqual(variables_schema["properties"]["country"]["type"], "string")
+ def test_openapi_spec_marks_hogql_variables_without_default_as_required(self):
+ """Regression for #54605."""
+ from products.product_analytics.backend.models.insight_variable import InsightVariable
+
+ with_default = InsightVariable.objects.create(
+ team=self.team,
+ name="Has Default",
+ code_name="has_default",
+ type=InsightVariable.Type.STRING,
+ default_value="default-value",
+ )
+ without_default = InsightVariable.objects.create(
+ team=self.team,
+ name="Required",
+ code_name="card_name",
+ type=InsightVariable.Type.STRING,
+ )
+
+ query_with_mixed_variables = {
+ "kind": "HogQLQuery",
+ "query": "SELECT * FROM events WHERE name = {variables.card_name}",
+ "variables": {
+ str(with_default.id): {
+ "variableId": str(with_default.id),
+ "code_name": "has_default",
+ "value": "default-value",
+ },
+ str(without_default.id): {
+ "variableId": str(without_default.id),
+ "code_name": "card_name",
+ },
+ },
+ }
+
+ create_endpoint_with_version(
+ name="endpoint-required-vars",
+ team=self.team,
+ query=query_with_mixed_variables,
+ created_by=self.user,
+ is_active=True,
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/endpoint-required-vars/openapi.json/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ spec = response.json()
+
+ variables_schema = spec["components"]["schemas"]["Variables"]
+ self.assertEqual(variables_schema.get("required"), ["card_name"])
+ self.assertNotIn("has_default", variables_schema.get("required", []))
+
+ operation = next(iter(spec["paths"].values()))["post"]
+ self.assertTrue(operation["requestBody"]["required"])
+
+ # `variables` itself must be required on EndpointRunRequest, otherwise
+ # a client sending {} passes validation without supplying card_name.
+ request_schema = spec["components"]["schemas"]["EndpointRunRequest"]
+ self.assertIn("variables", request_schema.get("required", []))
+
+ def test_openapi_spec_keeps_request_body_optional_when_all_variables_have_defaults(self):
+ """When every HogQL variable has a default value, nothing is required."""
+ from products.product_analytics.backend.models.insight_variable import InsightVariable
+
+ variable = InsightVariable.objects.create(
+ team=self.team,
+ name="Country Filter",
+ code_name="country",
+ type=InsightVariable.Type.STRING,
+ default_value="US",
+ )
+
+ query = {
+ "kind": "HogQLQuery",
+ "query": "SELECT * FROM events WHERE properties.$country = {variables.country}",
+ "variables": {str(variable.id): {"variableId": str(variable.id), "code_name": "country", "value": "US"}},
+ }
+
+ create_endpoint_with_version(
+ name="endpoint-optional-vars",
+ team=self.team,
+ query=query,
+ created_by=self.user,
+ is_active=True,
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/endpoint-optional-vars/openapi.json/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ spec = response.json()
+
+ variables_schema = spec["components"]["schemas"]["Variables"]
+ self.assertNotIn("required", variables_schema)
+
+ operation = next(iter(spec["paths"].values()))["post"]
+ self.assertFalse(operation["requestBody"]["required"])
+
+ request_schema = spec["components"]["schemas"]["EndpointRunRequest"]
+ self.assertNotIn("variables", request_schema.get("required", []))
+
+ def test_build_variables_schema_marks_breakdown_required_on_materialized_insight(self):
+ """Materialized insights resolve the breakdown column at materialization
+ time, so callers have to supply the value at execution. Non-materialized
+ insights fall back to the saved filter so the breakdown stays optional."""
+ from products.endpoints.backend.openapi import _build_variables_schema
+
+ trends_query = {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ "breakdownFilter": {"breakdown": "$browser", "breakdown_type": "event"},
+ }
+
+ schema = _build_variables_schema(trends_query, is_materialized=True, team_id=self.team.id)
+ assert schema is not None
+ self.assertIn("$browser", schema["properties"])
+ self.assertEqual(schema.get("required"), ["$browser"])
+
+ schema_non_materialized = _build_variables_schema(trends_query, is_materialized=False, team_id=self.team.id)
+ assert schema_non_materialized is not None
+ self.assertIn("$browser", schema_non_materialized["properties"])
+ self.assertNotIn("required", schema_non_materialized)
+
def test_openapi_spec_variable_types(self):
from products.product_analytics.backend.models.insight_variable import InsightVariable