Posthog.Client (posthog v1.1.0)

View Source

Low-level HTTP client for interacting with PostHog's API.

This module handles the direct HTTP communication with PostHog's API endpoints. It provides functions for:

  • Sending event capture requests
  • Processing batch events
  • Retrieving feature flag information

While this module can be used directly, it's recommended to use the higher-level functions in the Posthog module instead.

Configuration

The client uses the following configuration from your application:

config :posthog,
  api_url: "https://us.i.posthog.com",  # Required
  api_key: "phc_your_project_api_key", # Required
  json_library: Jason,                 # Optional (default: Jason)
  enabled_capture: true,               # Optional (default: true)
  http_client: Posthog.HTTPClient.Hackney,  # Optional (default: Posthog.HTTPClient.Hackney)
  http_client_opts: [                  # Optional
    timeout: 5_000,    # 5 seconds
    retries: 3,        # Number of retries
    retry_delay: 1_000 # 1 second between retries
  ]

Disabling capture

When enabled_capture is set to false:

This is useful for:

  • Development and test environments where you don't want to pollute your PostHog instance
  • Situations where you need to temporarily disable tracking

Example configuration for disabling the client:

# config/dev.exs or config/test.exs
config :posthog,
  enabled_capture: false

API Endpoints

The client interacts with the following PostHog API endpoints:

  • /capture - For sending individual and batch events
  • /decide - For retrieving feature flag information

Error Handling

All functions return a result tuple:

  • {:ok, response} for successful requests
  • {:error, response} for failed requests with a response
  • {:error, term()} for other errors (network issues, etc.)

Examples

# Capture an event
Posthog.Client.capture("page_view", "user_123")

# Send batch events
events = [
  {"page_view", "user_123", %{}},
  {"click", "user_123", %{}}
]
Posthog.Client.batch(events, timestamp: DateTime.utc_now())

# Get feature flags
Posthog.Client.feature_flags("user_123", groups: %{team: "engineering"})

Summary

Types

Cache key for the $feature_flag_called event.

Distinct ID for the person or group.

Event name, can be either an atom or a binary string.

Feature flag specific options that should not be passed to capture events.

HTTP headers in the format expected by :hackney.

Options that can be passed to API requests.

Properties that can be attached to events or feature flag requests.

Response from the PostHog API. Contains the status code, headers, and parsed JSON body (if any).

Result of a PostHog operation.

Timestamp for events. Can be a DateTime, NaiveDateTime, or ISO8601 string.

Functions

Sends multiple events to PostHog in a single request.

Retrieves information about a specific feature flag for a given distinct ID.

Retrieves feature flags for a given distinct ID.

Types

cache_key()

@type cache_key() :: {:feature_flag_called, binary(), binary()}

Cache key for the $feature_flag_called event.

distinct_id()

@type distinct_id() :: binary()

Distinct ID for the person or group.

event()

@type event() :: atom() | binary()

Event name, can be either an atom or a binary string.

feature_flag_opts()

@type feature_flag_opts() :: opts() | [{:send_feature_flag_event, boolean()}]

Feature flag specific options that should not be passed to capture events.

  • :send_feature_flag_event - Whether to capture the $feature_flag_called event (default: true)

headers()

@type headers() :: [{binary(), binary()}]

HTTP headers in the format expected by :hackney.

opts()

@type opts() :: [
  headers: headers(),
  groups: map(),
  group_properties: map(),
  person_properties: map(),
  timestamp: timestamp(),
  uuid: Uniq.UUID.t()
]

Options that can be passed to API requests.

  • :headers - Additional HTTP headers to include in the request
  • :groups - Group properties for feature flag evaluation
  • :group_properties - Additional properties for groups
  • :person_properties - Properties for the person
  • :timestamp - Custom timestamp for events
  • :uuid - Custom UUID for the event

properties()

@type properties() :: %{optional(atom() | String.t()) => term()}

Properties that can be attached to events or feature flag requests.

response()

@type response() :: %{status: pos_integer(), headers: headers(), body: map() | nil}

Response from the PostHog API. Contains the status code, headers, and parsed JSON body (if any).

result()

@type result() :: {:ok, response()} | {:error, response() | term()}

Result of a PostHog operation.

timestamp()

@type timestamp() :: String.t()

Timestamp for events. Can be a DateTime, NaiveDateTime, or ISO8601 string.

Functions

batch(events, opts)

Sends multiple events to PostHog in a single request.

Parameters

  • events - List of event tuples in the format {event_name, distinct_id, properties}
  • opts - Additional options (see opts/0)
  • headers - Additional HTTP headers

Examples

events = [
  {"page_view", "user_123", %{}},
  {"click", "user_123", %{button: "signup"}}
]

Posthog.Client.batch(events, %{timestamp: DateTime.utc_now()})

batch(events, opts, headers)

@spec batch([{event(), distinct_id(), properties()}], opts(), headers()) :: result()

capture(event, distinct_id, properties \\ %{}, opts \\ [])

@spec capture(event(), distinct_id(), properties(), opts()) :: result()

Captures a single event in PostHog.

Parameters

  • event - The name of the event (string or atom)
  • params - Event properties including :distinct_id
  • opts - Additional options (see opts/0)

Examples

# Basic event
Posthog.Client.capture("page_view", "user_123")

# Event with properties and timestamp
Posthog.Client.capture("purchase", "user_123", %{
  product_id: "123",
  price: 99.99
}, timestamp: DateTime.utc_now())

# Event with custom headers
Posthog.Client.capture("login", "user_123", %{}, headers: [{"x-forwarded-for", "127.0.0.1"}])

feature_flag(flag, distinct_id, opts \\ [])

@spec feature_flag(binary(), binary(), feature_flag_opts()) :: result()

Retrieves information about a specific feature flag for a given distinct ID.

Parameters

  • flag - The name of the feature flag
  • distinct_id - The unique identifier for the user
  • opts - Optional parameters for the feature flag request

Examples

# Boolean feature flag
{:ok, flag} = Posthog.feature_flag("new-dashboard", "user_123")
# Returns: %Posthog.FeatureFlag{name: "new-dashboard", payload: true, enabled: true}

# Multivariate feature flag
{:ok, flag} = Posthog.feature_flag("pricing-test", "user_123")
# Returns: %Posthog.FeatureFlag{
#   name: "pricing-test",
#   payload: %{"price" => 99, "period" => "monthly"},
#   enabled: "variant-a"
# }

feature_flags(distinct_id, opts)

@spec feature_flags(binary(), opts()) :: result()

Retrieves feature flags for a given distinct ID.

Parameters

  • distinct_id - The unique identifier for the user
  • opts - Additional options (see opts/0)

Examples

# Basic feature flags request
Posthog.Client.feature_flags("user_123")

# With group properties
Posthog.Client.feature_flags("user_123",
  groups: %{company: "company_123"},
  group_properties: %{company: %{industry: "tech"}}
)