PostHog OpenAPI Client

0.0.12 · active · verified Tue Apr 21

This package provides a TypeScript client for interacting with the PostHog API, automatically generated from the PostHog OpenAPI schema. It aims to offer a type-safe and convenient way to access PostHog's functionalities programmatically, including managing events, persons, and insights. Currently at version 0.0.12, it is in its early stages of development, meaning the API surface may evolve rapidly and breaking changes are likely before a stable 1.0 release. The package is primarily designed for TypeScript environments and relies on environment variables for API key and base URL configuration. Its key differentiator is providing a pre-generated, typed client, saving developers the effort of manual API request handling and type definition.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `PosthogAPIClient` using environment variables and then make authenticated API calls to fetch events and persons from your PostHog instance.

import { PosthogAPIClient } from 'posthog-openapi-client';

// Ensure environment variables are set:
// export POSTHOG_PERSONAL_API_KEY=YOUR_POSTHOG_API_KEY
// export POSTHOG_BASE_URL="https://eu.posthog.com" or "https://app.posthog.com"

const baseUrl = process.env.POSTHOG_BASE_URL ?? 'https://app.posthog.com';
const apiKey = process.env.POSTHOG_PERSONAL_API_KEY ?? '';

if (!apiKey) {
  console.error('Error: POSTHOG_PERSONAL_API_KEY environment variable is not set.');
  process.exit(1);
}

// Initialize the client with base URL and API key
const client = new PosthogAPIClient({
  BASE: baseUrl,
  TOKEN: apiKey
});

async function fetchSomeData() {
  try {
    // Example: Fetch recent events
    // The actual method names and parameters depend on the generated client's structure.
    // Assuming 'events' is a service and 'list' is a method on it.
    const events = await client.events.list({
      limit: 5,
      // You might need to specify a project ID or other filters depending on your PostHog setup
      // project_id: 123,
    });
    console.log(`Successfully fetched ${events.results?.length ?? 0} events.`);
    if (events.results && events.results.length > 0) {
      console.log('First event:', events.results[0]);
    }

    // Example: Fetch a list of persons
    const persons = await client.persons.list({ limit: 3 });
    console.log(`Successfully fetched ${persons.results?.length ?? 0} persons.`);
    if (persons.results && persons.results.length > 0) {
      console.log('First person:', persons.results[0]);
    }

  } catch (error) {
    console.error('Failed to interact with PostHog API:', error);
    if (error instanceof Error) {
      console.error('Error message:', error.message);
    }
  }
}

fetchSomeData();

view raw JSON →