PostHog OpenAPI Client
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
-
Error: POSTHOG_PERSONAL_API_KEY environment variable is not set.
cause The `POSTHOG_PERSONAL_API_KEY` environment variable is missing or empty, which the client uses for authentication.fixSet the `POSTHOG_PERSONAL_API_KEY` environment variable in your shell (e.g., `export POSTHOG_PERSONAL_API_KEY=YOUR_KEY`) or pass it directly to the client constructor: `new PosthogAPIClient({ TOKEN: 'YOUR_KEY', ... })`. -
TypeError: Cannot read properties of undefined (reading 'list')
cause An API service module (e.g., `client.events`) or method (e.g., `client.events.list`) does not exist on the client instance, likely due to an outdated client or a typo.fixVerify the exact structure and method names by inspecting the generated client code or the PostHog API documentation. Ensure your `posthog-openapi-client` package is up-to-date with the latest PostHog API schema. -
AxiosError: Network Error (or similar HTTP client error)
cause The client failed to connect to the PostHog API, often due to an incorrect `POSTHOG_BASE_URL`, network issues, or CORS restrictions in browser environments.fixCheck that `POSTHOG_BASE_URL` is correctly set (e.g., `https://app.posthog.com` or `https://eu.posthog.com`). Verify your network connection and ensure no firewall or proxy is blocking access. For browser usage, check for CORS policies.
Warnings
- breaking As a pre-1.0.0 package (version 0.0.12), the API surface is unstable. Expect frequent breaking changes to method names, parameter types, and response structures in minor and patch releases.
- gotcha The client relies on `POSTHOG_PERSONAL_API_KEY` and `POSTHOG_BASE_URL` environment variables by default. Forgetting to set these will lead to authentication or connection errors at runtime.
- gotcha The client is generated from PostHog's OpenAPI schema. If PostHog updates its API and a new version of this package isn't released, your client might become out-of-date, potentially leading to incorrect types or missing API endpoints.
Install
-
npm install posthog-openapi-client -
yarn add posthog-openapi-client -
pnpm add posthog-openapi-client
Imports
- PosthogAPIClient
const { PosthogAPIClient } = require('posthog-openapi-client');import { PosthogAPIClient } from 'posthog-openapi-client'; - Configuration options
import { PosthogAPIClient } from 'posthog-openapi-client'; const client = new PosthogAPIClient({ BASE: '...', TOKEN: '...' }); - API service modules (e.g., events)
const response = await client.events.list();
Quickstart
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();