Generated banner for Creating An Endpoint
Generated logo for Creating An Endpoint

Creating An Endpoint

PostHogOfficialPublished by PostHog

  • Skill
  • Workflow
  • Data and AI
  • MIT
  • No issues found

From the author

Create a PostHog endpoint with the right shape on the first try — covers query kind choice, name conventions, what to expose as variables (HogQL code_name vs insight breakdown), data_freshness_seconds, and whether to materialise on day one. Use when the user says "create an endpoint", "expose this query as an API", "turn this insight into an endpoint", or asks for help structuring a new endpoint. Steers away from common mistakes: materialising a query with cohort breakdowns or an ineligible compare query, inline-only variables on a materialised endpoint, unbounded date ranges, ambiguous names.
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a systematic approach to creating PostHog endpoints, ensuring they are performant, maintainable, and correctly configured. It guides users through naming conventions, query selection (HogQL vs. Insight), variable definition, and the critical decision of whether to materialise the endpoint for performance. By following this workflow, users avoid common pitfalls like ambiguous naming, unbounded date ranges, and improper materialisation settings.

What it does

  • Validates whether a query is suitable for an endpoint or better served by other tools.
  • Provides best practices for naming endpoints to ensure URL stability.
  • Helps define input variables for dynamic query execution.
  • Guides the selection of data_freshness_seconds to balance latency and recompute costs.
  • Assists in deciding when to enable materialisation for high-traffic queries.
  • Ensures endpoints are tested with sample payloads before final hand-off.

When to use it

  • When you need to expose a PostHog query as a callable HTTP route for external systems.
  • When you want to turn a saved insight or HogQL query into a reusable API.
  • When you are unsure about the performance implications of your query structure.
  • When you need to configure caching or materialisation for a data-heavy endpoint.

Advantages

  • Reduces the risk of creating unstable or poorly performing API routes.
  • Ensures consistent naming and versioning practices.
  • Optimizes query performance through informed materialisation decisions.
  • Prevents common configuration errors like missing variable defaults or ineligible materialisation.

Usage examples

“Create an endpoint for my monthly active users query.”
The agent will guide you through naming the endpoint, selecting the query type, defining variables like date ranges, setting the cache TTL, and determining if materialisation is appropriate.
“How do I expose this insight as an API?”
The agent will help you extract the underlying query, configure it as an endpoint, and set up the necessary variables and freshness settings.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/posthog/creating-an-endpoint/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip creating-an-endpoint.zip -d .agents/skills

Documentation by PostHog

Creating an endpoint

This skill walks through creating a new endpoint with the right configuration. Endpoints expose saved HogQL or insight queries as callable HTTP routes — the configuration choices made at creation time determine cost, latency, and how callers integrate.

The materialisation deep-dive lives at references/materializing.md. Pull it in when the materialisation decision is non-obvious.

When to use this skill

  • "Create an endpoint for [query]"

  • "Expose this insight as an API"

  • "Help me turn this HogQL into a callable endpoint"

  • A new caller (mobile app, customer-facing dashboard, downstream pipeline) needs PostHog data and the user is choosing how to deliver it

Decisions to make in order

1. Should this even be an endpoint?

Endpoints are right when:

  • An external system (someone else's code) needs to call PostHog for data

  • The query is stable — not exploratory analysis

  • The shape is reusable — same query with different parameters

Endpoints are wrong when:

  • An internal PostHog dashboard or insight needs the data — use the insight directly; an endpoint only adds an external API surface you don't need internally

  • One-off, exploratory analysis — use the execute-sql tool (or the SQL editor) directly

Heavy aggregation is not a reason to avoid an endpoint. Endpoints are themselves saved queries, and a heavy, frequently-called aggregation is often the best case for an endpoint with materialisation turned on.

If the user is unsure, ask what's calling the endpoint and what shape they expect.

2. Pick a name

Names are URL-safe (letters, numbers, hyphens, underscores), start with a letter, max 128 chars, must be unique within the project. Lean toward:

  • Descriptive over generic — weekly_active_users_by_org over metrics

  • Snake_case — matches how the name appears in code paths and URLs

  • No version in the name — versions are managed by the endpoint itself

  • No "endpoint" in the name — redundant

The name appears in the URL: /api/projects/{team_id}/endpoints/{name}/run. It's not trivially renameable later (callers depend on the path) — get it right at creation.

3. Pick the query kind

Two options exist:

  • HogQL (HogQLQuery) — raw SQL written by the user. Variables defined via {variables.x} syntax, matched on code_name. Recommended for new endpoints when the caller cares about the exact column shape of the response.

  • Insight — wraps an existing insight definition. Best supported for TrendsQuery, LifecycleQuery, and RetentionQuery: these can be materialised, and the breakdown can act as a variable (Trends and Retention only; Lifecycle has no breakdown). Other insight kinds such as FunnelsQuery can run inline but cannot be materialised and don't expose breakdown variables — rewrite those as HogQL if you need either.

HogQL is the more flexible choice. Pick insight only when the user is genuinely re-publishing an existing insight (see "Creating from an existing insight" below) rather than building a new query.

4. Decide which inputs become variables

Anything that should change per-caller goes in variables; the rest is hard-coded in the query.

For HogQL endpoints, variables are declared in the query payload with code_name, type, and default. Each execution call passes { "variables": { "<code_name>": value } }.

Common patterns:

  • Time windows: date_from, date_to, or a single lookback_days integer

  • Identity filters: user_id, account_id, team_id

  • Pagination control beyond limit / offset (these are first-class on the run endpoint already)

For insight endpoints, the breakdown property acts as the variable (Trends and Retention only — Lifecycle has no breakdown). Pass the breakdown property name as the key. date_from / date_to are accepted as variables only on non-materialised insight endpoints — a materialised endpoint bakes its date range into the view, so callers can't shift the window.

Avoid:

  • Variables that change the shape of the result — keep the columns stable. If callers need fundamentally different result shapes, ship separate endpoints.

  • Variables that bypass safety — don't expose a where_clause variable that lets callers inject arbitrary SQL.

Creating from an existing insight

There's no server-side "make an endpoint from insight N" operation. To do it: read the insight's query (via the insight tools), pass that query to endpoint-create, and set derived_from_insight to the insight's short id so the origin is recorded. The endpoint then owns its own copy of the query — later edits to the insight don't propagate. Starting from scratch instead? Build the query first with the insight / sql-variables tools, then create the endpoint from it.

5. Set data_freshness_seconds

This one field does two jobs, so set it deliberately:

  1. Cache TTL — results are served from cache until they're this many seconds old.

  2. Materialisation refresh frequency — on a materialised endpoint, this is also how often the warehouse recomputes the materialised view.

So a lower value means fresher data and more frequent recompute/refresh cost; a higher value is cheaper on both counts but staler.

The value must be one of a fixed set: 900 (15 min), 1800 (30 min), 3600 (1 h), 21600 (6 h), 43200 (12 h), 86400 (24 h, default), 604800 (7 d). There is no sub-15-minute option — 900 is the floor.

data_freshness_secondsWhen to pick it
900–1800Freshest available — dashboards where staleness is visible
3600–43200Most cases — fresh enough for product usage, cheap to recompute
86400–604800Reports, weekly/daily metrics, anything aggregated over long periods

Bias toward higher values unless the user explicitly needs fresher data. On a materialised endpoint, remember this also sets the refresh cadence.

6. Decide on day-one materialisation

See references/materializing.md for the full decision tree. Short version:

  • Recommend materialisation when the endpoint will be called frequently, latency matters, and the user can tolerate staleness equal to the refresh interval (typically 5-15 minutes for scheduled materialisation, or hourly).

  • Skip materialisation for low-traffic endpoints, exploratory new endpoints (you don't know yet if it'll get called), and queries where freshness is critical.

If unsure, create unmaterialised and add is_materialized: true later once usage stabilises. That avoids paying for materialisation on a query nobody ends up calling.

Workflow

  1. Confirm the use case (step 1 above). If it's not actually a fit for an endpoint, recommend the alternative.

  2. Agree a name with the user.

  3. Walk through the query — confirm it's HogQL or insight, and that the columns/shape make sense.

  4. Identify what should be a variable. Show the user the variable declaration syntax.

  5. Pick data_freshness_seconds based on the user's freshness requirement (ask if not clear) — remembering it also sets the materialisation refresh cadence.

  6. Make the materialisation call. If on the fence, ship without and revisit later.

  7. Call endpoint-create with the agreed config.

  8. Confirm by calling endpoint-run with a sample payload to verify the response shape.

  9. Hand off to consuming-endpoints-from-client-code if the user is about to wire it up.

Example interaction

User: "I want to expose our monthly active users count as an API
       for our analytics partner"

Agent:
- "Quick check: is the partner going to call this on demand, or
   should we be pushing data to them? Endpoints are pull-only."
- User: "On demand"
- "Got it. A few choices:
   - Name: how about monthly_active_users? Lowercase, descriptive,
     no version baggage.
   - The query — is it HogQL or are you exposing an existing insight?
     HogQL gives you exact column control; insight reuses what you've
     already built.
   - What should the partner be able to filter by? Org, time window,
     both?
   - How fresh? If MAU drifts within a day is fine, we can cache
     results for 1-24 hours and serve almost everything from cache.
   - Materialisation: if the partner is going to hit this many times
     per day, materialising it would make responses near-instant.
     The trade-off is ~10-15 minute staleness.

   What's your starting point on these?"

[user picks: HogQL, lookback_days + org_id variables, 3600s TTL,
 not materialised yet]

- endpoint-create monthly_active_users {query, variables, ...}
- endpoint-run with sample payload {org_id: "test", lookback_days: 30}
- "Created and tested. Want help wiring up the client code?
   That's consuming-endpoints-from-client-code."

Important notes

  • The name lives in the URL. Changing it later requires migrating callers. Pick well.

  • HogQL endpoints are more flexible than insight endpoints. Default to HogQL unless the user has a specific reason to wrap an existing insight.

  • Variables with no default fail at call time. Always set defaults during creation so the endpoint is testable from the playground without specifying every variable.

  • Materialised endpoints require all variables to be passed. Calls without them are rejected — this is intentional (security: prevents returning unfiltered data). Pair the materialisation recommendation with a note to the user about which variables become required. (Optional/partial variables on materialised endpoints are a known limitation the PostHog team plans to lift — if it's blocking the user, nudge them via the agent-feedback tool.)

  • Don't enable materialisation on a query that isn't eligible. Use endpoints-materialization-preview first to confirm eligibility and see the rejection reason if any.

  • Endpoints are not stable forever. When the user changes the query, a new version is created automatically (the old version stays accessible via ?version=N). data_freshness_seconds and materialisation are per-version. Adjust as the endpoint evolves.

  • Recommend callers pin to a version. Tell the user to call with ?version=N rather than relying on "latest" — that way a future query edit (which cuts a new version) can't silently change their results. They bump the pinned version deliberately once they've validated the new one.

  • Share friction via agent-feedback. If a limitation gets in the way (eligibility rules, required variables, the TTL enum), send the PostHog team a note — it's how the product and these tools improve.

Files

references/materializing.md

Materialising an endpoint

Materialisation pre-computes an endpoint's query into a saved view that's refreshed on a schedule. Reads become near-instant but the data is as stale as the refresh interval. This reference is the detailed flow behind step 6 of creating-an-endpoint and the step 2 decision in diagnosing-endpoint-performance.

When materialisation is the right call

SignalMeans
Endpoint is called more than ~10 times per minute, sustainedReads will dominate cost — pre-computing saves a lot
Query takes more than ~1s of ClickHouse time inlineLatency on the read path matters; materialisation collapses it
Callers can tolerate 5-15 minute stalenessThe refresh interval becomes the freshness floor
Variables are bounded — small known set of valuesBucket overrides become tractable; the materialised view stays small

If two or more of these apply, materialise. If none apply, don't.

When materialisation is wrong

  • Real-time data requirement. Anything that drives a "live" UI element where users notice 10-minute lag.

  • High-cardinality variables. If callers pass arbitrary user_id values, each materialised bucket is tiny and the refresh churn outweighs the read savings.

  • Low-traffic endpoint. If it's called once a day, the materialisation refresh costs more than the inline reads would.

  • Cohort breakdowns (insight endpoints). Regular property breakdowns materialise fine, but cohort breakdowns are rejected. Compare mode can materialise for Trends endpoints. It stores and computes both periods, so expect about twice the storage and refresh work. Use endpoints-materialization-preview to confirm eligibility.

  • Query reads now() / today() directly. Replace with a variable; otherwise the materialised result is anchored to the refresh time, not the call time.

Eligibility rules

Eligibility is enforced server-side (and surfaced by endpoints-materialization-preview). Common rejection reasons:

ReasonWhat it meansFix
Cohort breakdowns are not supportedCohort breakdowns produce a UNION ALL the transform can't tag by seriesUse a property breakdown, or split into separate endpoints, one per cohort
Compare mode is only supportedCompare mode is set on a query that is not a Trends queryKeep it inline, drop compare mode, or expose the comparison window as a variable
Query has unresolved variablesA variable in the query has no default and the materialisation can't pick a valueSet defaults for all variables
Query references non-deterministic functionsnow(), today(), rand() change between refresh runsReplace with a date_from / date_to variable
CTE variables with JOINs … not supportedA variable filter combined with a top-level JOIN changes joined-row cardinality, silently producing wrong results (e.g. LEFT JOIN non-matches lose the variable column)Filter inside a subquery/CTE, then join the result — don't apply the variable across the JOIN
Query kind not supportedSome query kinds (e.g. funnels) don't have a materialisation path yetRewrite in HogQL

Always call endpoints-materialization-preview before enabling — it returns the exact rejection reason if any, plus the transformed query so the user can sanity-check what will be materialised.

Variables become WHERE filters

When you call a materialised endpoint, the materialised view is queried with a WHERE clause built from the variables you pass. This has two implications:

  1. All declared variables must be passed. Calls missing any materialised variable are rejected. This is a security feature — it prevents callers from getting back the entire pre-aggregated dataset by omitting filters.

  2. The materialised view contains all rows across all variable combinations. If your variables have N values each and there are M variables, the view's row count is roughly the product. Bound this by either:

    • Picking variables with small cardinality

    • Bucketing range/time variables with bucket_overrides (see below)

Bucket overrides — making range variables materialisable

A continuous range variable — a timestamp or numeric filter like WHERE timestamp >= {variables.since} — has effectively unlimited distinct values, so the view can't pre-compute every one. bucket_overrides fixes this by pre-aggregating that column at a coarser grain and filtering at read time. Pass a map of column → bucket function:

{ "bucket_overrides": { "timestamp": "hour" } }

Supported functions: minute, fifteen_minutes, hour, day, week, month (each is a toStartOf… rollup). Pick the coarsest bucket the caller can tolerate: day keeps the view small and refreshes cheap; minute is large and expensive. The caller still passes their exact value — the view just answers from the bucketed rollup. Run endpoints-materialization-preview to see which range variables were detected and confirm the bucketing before you enable.

Refresh schedule

The refresh interval determines staleness. Available intervals are tied to the data warehouse saved query schedule — typically 5min, 15min, hourly, or daily. Pick the longest interval that satisfies the user's SLA.

Materialisation status is tracked on the saved query (DataWarehouseSavedQuery) backing each version. endpoint-materialization-status returns the last run time, status, and any error. If it shows Failed, the inline path still works (the endpoint isn't broken — it's just slower than expected), but the materialised data is stale.

Per-version materialisation

Each endpoint version has its own materialised view, named {endpoint_name}_v{version}. When you create a new version (by changing the query), the new version starts unmaterialised by default. The old version's materialisation continues until you explicitly disable it via endpoint-update with version and is_materialized: false.

This means a project can accumulate unused materialised versions — old versions of an endpoint that nobody calls but are still being refreshed. The auditing-endpoints skill catches this by reading per-version last_executed_at from endpoint-versions.

Operational notes

  • Enabling materialisation is free to start. No backfill — the first refresh kicks off the initial population. The endpoint stays callable inline during that time.

  • Disabling materialisation is reversible. Set is_materialized: false and the materialised view is dropped on the next cleanup pass. Re-enabling re-creates it.

  • Storage costs add up. Many materialised views with high-cardinality variables can dominate warehouse storage. When the user's project is hitting cost caps, materialisation cleanup is usually the first lever.

  • Materialisation failures don't block reads. The endpoint stays callable inline if the refresh fails — the user gets stale data with longer latency, not an outright outage. Surface the failure but don't escalate it as a blocker unless freshness is critical.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
PostHog
Publisher
PostHog (Official)
Source
PostHog/skills · skills/omnibus/creating-an-endpoint · commit a5d30e7
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by PostHog.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download creating-an-endpoint.zip