Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(endpoints): link examples to project secret keys (#107804)

Jovan Sakovic830831b3ab50
diff --git a/products/endpoints/frontend/endpoint-tabs/EndpointPlayground.test.tsx b/products/endpoints/frontend/endpoint-tabs/EndpointPlayground.test.tsx
new file mode 100644
index 000000000000..5289618599cc
--- /dev/null
+++ b/products/endpoints/frontend/endpoint-tabs/EndpointPlayground.test.tsx
@@ -0,0 +1,62 @@
+import { urls } from 'scenes/urls'
+
+import type { EndpointVersionType } from '~/types'
+
+import { generateEndpointPayload } from '../endpointSceneLogic'
+import {
+ generateNodeExample,
+ generatePythonExample,
+ generateTerminalExample,
+ PROJECT_SECRET_API_KEY_SETTINGS_SECTION,
+} from './EndpointPlayground'
+
+jest.mock('../endpointLogic', () => ({ endpointLogic: {} }))
+jest.mock('../endpointSceneLogic', () => ({ generateEndpointPayload: jest.fn() }))
+
+describe('EndpointPlayground code examples', () => {
+ const endpoint = {
+ endpoint_path: '/api/projects/1/endpoints/example-endpoint/run',
+ current_version: 1,
+ } as EndpointVersionType
+ const mockGenerateEndpointPayload = generateEndpointPayload as jest.MockedFunction<typeof generateEndpointPayload>
+
+ afterEach(() => {
+ jest.clearAllMocks()
+ })
+
+ it('links to project secret API key settings', () => {
+ expect(urls.settings(PROJECT_SECRET_API_KEY_SETTINGS_SECTION)).toBe('/settings/environment-secret-api-keys')
+ })
+
+ it.each([
+ ['terminal', generateTerminalExample, 'Bearer $POSTHOG_PROJECT_SECRET_API_KEY', "-d '{"],
+ ['Python', generatePythonExample, "os.environ['POSTHOG_PROJECT_SECRET_API_KEY']", 'data=json.dumps(payload)'],
+ ['Node.js', generateNodeExample, 'process.env.POSTHOG_PROJECT_SECRET_API_KEY', 'body: JSON.stringify(payload)'],
+ ])(
+ 'uses an environment API key and request payload in the %s example',
+ (_language, generateExample, environmentAccessExpression, payloadExpression) => {
+ mockGenerateEndpointPayload.mockReturnValue({ variables: { limit: 10 } })
+
+ const example = generateExample(endpoint, null)
+
+ expect(example).toContain(environmentAccessExpression)
+ expect(example).toContain(payloadExpression)
+ }
+ )
+
+ it.each([
+ ['terminal', generateTerminalExample, 'Bearer $POSTHOG_PROJECT_SECRET_API_KEY', "-d '{"],
+ ['Python', generatePythonExample, "os.environ['POSTHOG_PROJECT_SECRET_API_KEY']", 'data=json.dumps(payload)'],
+ ['Node.js', generateNodeExample, 'process.env.POSTHOG_PROJECT_SECRET_API_KEY', 'body: JSON.stringify(payload)'],
+ ])(
+ 'uses an environment API key without a request payload in the %s example',
+ (_language, generateExample, environmentAccessExpression, payloadExpression) => {
+ mockGenerateEndpointPayload.mockReturnValue({})
+
+ const example = generateExample(endpoint, null)
+
+ expect(example).toContain(environmentAccessExpression)
+ expect(example).not.toContain(payloadExpression)
+ }
+ )
+})
diff --git a/products/endpoints/frontend/endpoint-tabs/EndpointPlayground.tsx b/products/endpoints/frontend/endpoint-tabs/EndpointPlayground.tsx
index a16620454187..506dfb19b04c 100644
--- a/products/endpoints/frontend/endpoint-tabs/EndpointPlayground.tsx
+++ b/products/endpoints/frontend/endpoint-tabs/EndpointPlayground.tsx
@@ -58,7 +58,9 @@ function getEndpointUrl(endpointPath: string): string {
return `${window.location.origin}${endpointPath}`
}
-function generateTerminalExample(endpoint: EndpointVersionType, selectedVersion: number | null): string {
+export const PROJECT_SECRET_API_KEY_SETTINGS_SECTION = 'environment-secret-api-keys'
+
+export function generateTerminalExample(endpoint: EndpointVersionType, selectedVersion: number | null): string {
const payload = generateEndpointPayload(endpoint)
const hasPayload = Object.keys(payload).length > 0
const versionParam =
@@ -69,21 +71,21 @@ function generateTerminalExample(endpoint: EndpointVersionType, selectedVersion:
// If no payload and no version, omit the -d flag entirely
if (!hasPayload && !versionParam) {
return `curl -X POST ${getEndpointUrl(endpoint.endpoint_path)} \\
- -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY"`
+ -H "Authorization: Bearer $POSTHOG_PROJECT_SECRET_API_KEY"`
}
const payloadBody = formatPayloadForCodeExample(payload)
const dataContent = [payloadBody, versionParam].filter(Boolean).join(',\n')
return `curl -X POST ${getEndpointUrl(endpoint.endpoint_path)} \\
- -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" \\
+ -H "Authorization: Bearer $POSTHOG_PROJECT_SECRET_API_KEY" \\
-H "Content-Type: application/json" \\
-d '{
${dataContent}
}'`
}
-function generatePythonExample(endpoint: EndpointVersionType, selectedVersion: number | null): string {
+export function generatePythonExample(endpoint: EndpointVersionType, selectedVersion: number | null): string {
const payload = generateEndpointPayload(endpoint)
const hasPayload = Object.keys(payload).length > 0
const versionParam =
@@ -93,12 +95,13 @@ function generatePythonExample(endpoint: EndpointVersionType, selectedVersion: n
// If no payload and no version, omit payload variable entirely
if (!hasPayload && !versionParam) {
- return `import requests
+ return `import os
+import requests
url = "${getEndpointUrl(endpoint.endpoint_path)}"
headers = {
- 'Authorization': 'Bearer {POSTHOG_PERSONAL_API_KEY}'
+ 'Authorization': f"Bearer {os.environ['POSTHOG_PROJECT_SECRET_API_KEY']}"
}
response = requests.post(url, headers=headers)
@@ -108,14 +111,15 @@ print(response.json())`
const payloadBody = formatPayloadForCodeExample(payload)
const dataContent = [payloadBody, versionParam].filter(Boolean).join(',\n')
- return `import requests
+ return `import os
+import requests
import json
url = "${getEndpointUrl(endpoint.endpoint_path)}"
headers = {
'Content-Type': 'application/json',
- 'Authorization': 'Bearer {POSTHOG_PERSONAL_API_KEY}'
+ 'Authorization': f"Bearer {os.environ['POSTHOG_PROJECT_SECRET_API_KEY']}"
}
payload = {
@@ -126,7 +130,7 @@ response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.json())`
}
-function generateNodeExample(endpoint: EndpointVersionType, selectedVersion: number | null): string {
+export function generateNodeExample(endpoint: EndpointVersionType, selectedVersion: number | null): string {
const payload = generateEndpointPayload(endpoint)
const hasPayload = Object.keys(payload).length > 0
const versionParam =
@@ -141,7 +145,7 @@ function generateNodeExample(endpoint: EndpointVersionType, selectedVersion: num
const url = '${getEndpointUrl(endpoint.endpoint_path)}';
const headers = {
- 'Authorization': 'Bearer {POSTHOG_PERSONAL_API_KEY}'
+ 'Authorization': 'Bearer ' + process.env.POSTHOG_PROJECT_SECRET_API_KEY
};
fetch(url, {
@@ -162,7 +166,7 @@ const url = '${getEndpointUrl(endpoint.endpoint_path)}';
const headers = {
'Content-Type': 'application/json',
- 'Authorization': 'Bearer {POSTHOG_PERSONAL_API_KEY}'
+ 'Authorization': 'Bearer ' + process.env.POSTHOG_PROJECT_SECRET_API_KEY
};
const payload = {
@@ -361,7 +365,7 @@ export function EndpointPlayground(): JSX.Element {
</div>
<LemonDivider className="my-4" />
<div className="flex flex-col gap-4">
- <LemonLabel info="Create a personal API key and copy a code example to call this endpoint from your application.">
+ <LemonLabel info="Create a project secret API key with endpoint:read access and copy a code example to call this endpoint from your application.">
Example usage
</LemonLabel>
<div className="flex gap-2">
@@ -385,13 +389,13 @@ export function EndpointPlayground(): JSX.Element {
value={activeCodeExampleTab}
/>
<LemonButton
- to={urls.settings('user', 'personal-api-keys')}
+ to={urls.settings(PROJECT_SECRET_API_KEY_SETTINGS_SECTION)}
type="secondary"
size="small"
icon={<IconExternal />}
targetBlank
>
- Personal API keys
+ Project secret API keys
</LemonButton>
</div>
<div>