Create an endpoint with variables

This guide walks through creating an endpoint that accepts variables, allowing you to filter results at execution time. We'll create a customer-specific analytics endpoint that filters data by a customer_id property.

Step 1: Write your SQL query with a variable

Open the SQL editor and write a query that uses the {variables.variable_name} syntax:

SQL
SELECT
toDate(timestamp) AS date,
count() AS event_count
FROM events
WHERE
properties.customer_id = {variables.customer_id}
AND timestamp >= now() - INTERVAL 30 DAY
GROUP BY date
ORDER BY date
SQL query with variable in the editor

Step 2: Define the variable

In the Variables tab in the output pane, click Add variable, then New variable and fill in the modal.

  1. Name: A human-readable name (e.g., "Customer ID")
  2. Type: The variable type (String, Number, etc.)
  3. Default value: Optional default when no value is provided
Configuring a variable in the SQL editor

Step 3: Test your query

Enter a test value for your variable and run the query to verify it works:

Testing the query with a variable value

Step 4: Create the endpoint

Once your query works, click the Endpoint tab in the output pane:

  1. Enter a descriptive name (e.g., customer_events_by_day)
  2. Add an optional description
  3. Click Create endpoint
Creating an endpoint from a SQL query

Step 5: Execute with a variable

Now you can call your endpoint and pass the variable value:

Terminal
curl -X POST \
-H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" \
-H "Content-Type: application/json" \
-d '{"variables": {"customer_id": "acme-corp"}}' \
"<ph_app_host>/api/projects/{project_id}/endpoints/customer_events_by_day/run"

The response will only include events where properties.customer_id = 'acme-corp'.

Pay attention: Variables are required

If your endpoint has a variable defined, you must provide a value when executing. This is a safety feature to prevent accidentally returning unfiltered data.

Calling the endpoint without the required variable will return an error:

JSON
{
"detail": "Required variable 'customer_id' not provided"
}

Next steps

Community questions

Was this page useful?

Questions about this page? or post a community question.