### Install the Go SDK Source: https://docs.statsig.com/server/golangSDK Instructions for installing the Statsig Go SDK using the `go get` command or by adding it to your `go.mod` file. ```APIDOC ## Install the SDK Install the SDK via the `go get` CLI: ``` go get github.com/statsig-io/go-sdk ``` Or, add a dependency on the most recent version of the SDK in go.mod: ``` require ( github.com/statsig-io/go-sdk v1.26.0 ) ``` See the Releases tab in GitHub for the latest versions. ``` -------------------------------- ### Install PHP Core SDK with Composer Source: https://docs.statsig.com/server-core/migration-guides/php Install the PHP Core SDK using Composer and configure post-install scripts to run the provided setup file. ```bash composer require statsig/statsig-php-core // composer.json { "name": "awesome-php-project", ... "scripts": { ... "post-install-cmd": [ "cd vendor/statsig/statsig-php-core && php post-install.php" ], "post-update-cmd": [ "cd vendor/statsig/statsig-php-core && php post-install.php" ] } } ``` ```bash composer require statsig/statsigsdk ``` -------------------------------- ### Install Statsig Go SDK Source: https://docs.statsig.com/server/golangSDK Install the Statsig Go SDK using the `go get` command or by adding it to your go.mod file. ```go go get github.com/statsig-io/go-sdk ``` ```go require ( github.com/statsig-io/go-sdk v1.26.0 ) ``` -------------------------------- ### Install the Go SDK Source: https://docs.statsig.com/server/go Install the Statsig Go SDK using the go get command or by adding it as a dependency in your go.mod file. Check GitHub releases for the latest versions. ```bash go get github.com/statsig-io/go-sdk ``` ```go require ( github.com/statsig-io/go-sdk v1.26.0 ) ``` -------------------------------- ### Python DataAdapter Setup for Forward Proxy Cache Source: https://docs.statsig.com/infrastructure/forward-proxy Example of setting up a DataAdapter in Python to coordinate with a Forward Proxy Cache service. This setup helps the SDK initialize with cached values if the proxy is unavailable and syncs in the background. ```python class DataAdapter(IDataStore): def __init__(self): self.redis_cache = ExampleCache() def get(self, key: str): # IDlist isn't currently supported by proxy, so do normal lookup if "statsig.id_lists" in key: return self.cache.get(key) # This logic must stay in sync with statsig-forward-proxy else: hashed_key = "statsig::" + hashlib.sha256(key.encode()).hexdigest() return self.cache.hget(hashed_key, 'config') def set(self, key: str): # Don't implement set method if you are share the same cache between forward proxy and sdk, forward proxy will write to cache pass def shutdown(self): self.cache.shutdown() ``` -------------------------------- ### Initialize OpenTelemetry Tracing (Custom Setup) Source: https://docs.statsig.com/ai-evals/node If you already have your own OTel setup with `NodeSDK`, you only need to initialize Statsig's OTel tracing and use the processor created by `initializeTracing()`. This example shows how to integrate Statsig's tracing processor into an existing `NodeSDK` instance. ```APIDOC ## Initialize Tracing with Existing NodeSDK ### Description Initializes Statsig's OpenTelemetry tracing and integrates its processor into an existing `NodeSDK` instance, allowing for custom tracing configurations. ### Method `initializeTracing(options?: InitializeOptions)` ### Parameters #### Options - **skipGlobalContextManagerSetup** (boolean) - Optional - Prevents creating a global context manager. - **exporterOptions** (StatsigOTLPTraceExporterOptions) - Optional - Options to pass to the StatsigOTLPTraceExporter. - **serviceName** (string) - Optional - The service name for resource attributes. - **version** (string) - Optional - The service version for resource attributes. - **environment** (string) - Optional - The service environment for resource attributes. ### Request Example ```javascript import { NodeSDK } from '@opentelemetry/sdk-node'; import { PeriodicExportingMetricReader, ConsoleMetricExporter } from '@opentelemetry/sdk-metrics'; import { initializeTracing } from '@statsig/statsig-ai/otel'; const { processor } = initializeTracing({ skipGlobalContextManagerSetup: true, exporterOptions: { sdkKey: process.env.STATSIG_SDK_KEY!, }, }); const sdk = new NodeSDK({ spanProcessors: [processor], metricReader: new PeriodicExportingMetricReader({ exporter: new ConsoleMetricExporter(), }), }); sdk.start(); export { sdk }; ``` ``` -------------------------------- ### Install All Skills Source: https://docs.statsig.com/integrations/agent-skills Install every skill available in the repository by using the '--all' flag with the 'skills' CLI. ```bash npx skills add statsig-io/agent-skills --all ``` -------------------------------- ### Configure Forward Proxy for Network Requests Source: https://docs.statsig.com/server/pythonSDK Set up a forward proxy for the SDK to use when downloading configuration specs. This example shows basic GRPC_WEBSOCKET setup. ```python proxyAddress = "0.0.0.0:50051" // local address update to your address Statsig.initialize(secret_key, StatsigOptions(proxy_configs={ NetworkEndpoint.DOWNLOAD_CONFIG_SPECS: ProxyConfig(NetworkProtocol.GRPC_WEBSOCKET, proxyAddress)})) ``` -------------------------------- ### Install Statsig Java SDK Core Library (Maven) Source: https://docs.statsig.com/server-core/java-core Install the platform-independent core library. This is the first step in the advanced two-part installation process. ```xml com.statsig javacore X.X.X ``` -------------------------------- ### Full Example: Bootstrap Client SDK with Server-Generated Response Source: https://docs.statsig.com/server-core/python-core This example demonstrates initializing the server SDK, generating a client initialize response with specific parameters, and returning it to the client for SDK initialization. ```python # Server-side code import json from statsig_python_core import Statsig, StatsigUser, StatsigOptions from flask import Flask, request, jsonify app = Flask(__name__) # Initialize the server SDK options = StatsigOptions() statsig = Statsig('server-secret-key', options) statsig.initialize().wait() # In your API endpoint handler @app.route('/statsig-bootstrap') def statsig_bootstrap(): # Create a user object from the request user = StatsigUser( user_id=request.args.get('userID', ''), email=request.args.get('email'), ip=request.remote_addr, user_agent=request.headers.get('User-Agent') ) # Generate the client initialize response response_data = statsig.get_client_initialize_response( user, hash='djb2', client_sdk_key='client-sdk-key' ) # Parse the JSON response statsig_values = json.loads(response_data) # Return the values to the client return jsonify({'statsigValues': statsig_values}) ``` ```javascript // Client-side code using @statsig/js-client import { Statsig } from '@statsig/js-client'; // Fetch bootstrap values from your API const response = await fetch('/statsig-bootstrap'); const { statsigValues } = await response.json(); // Initialize the client SDK with the bootstrap values await Statsig.initialize({ sdkKey: 'client-sdk-key', initializeValues: statsigValues, }); ``` -------------------------------- ### Complete Fastly Integration Example Source: https://docs.statsig.com/integrations/fastly A complete example demonstrating the Statsig Fastly integration, including client initialization, gate checking, event logging, and flushing. ```javascript import { StatsigFastlyClient } from "@statsig/serverless-client/fastly"; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const client = new StatsigFastlyClient("client-LhxVWHSeZt2uor********"); const initResult = await client.initialzeFromFastly( "kv", "7b12fnfm7po7*********", "statsig-3htllY8X**********", "7NaRxS6RMGE-DTp*******" ); const user = { userID: Math.random().toString().substring(2, 5) }; const value = client.checkGate("pass_gate", user); client.logEvent("fastly_gate_check", user, value.toString()); event.waitUntil(client.flush()); return new Response(JSON.stringify({ kv, user }), { status: 200, ``` -------------------------------- ### Dummy Persistent Storage Adapter Example Source: https://docs.statsig.com/server/rubySDK An example implementation of the IUserPersistentStorage interface for testing purposes. ```APIDOC ## Dummy Persistent Storage Adapter Example ```ruby class DummyPersistentStorageAdapter < Statsig::Interfaces::IUserPersistentStorage attr_accessor :store def initialize @store = {} end def load(key) return nil unless @store&.key?(key) @store[key] end def save(key, data) @store[key] = data end end ``` ``` -------------------------------- ### Full Server-Side Example for Client Bootstrap Source: https://docs.statsig.com/server-core/node-core A complete server-side example demonstrating how to initialize the Node Core SDK, create a user object, generate a client initialize response with filters, and return it to the client. ```typescript import { Statsig, StatsigUser } from '@statsig/node-core'; await Statsig.initialize('server-secret-key'); app.get('/statsig-bootstrap', (req, res) => { const user = new StatsigUser({ userID: req.query.userID || '', email: req.query.email, ip: req.ip, userAgent: req.headers['user-agent'], }); const values = Statsig.getClientInitializeResponse(user, { hashAlgorithm: 'djb2', featureGateFilter: new Set(['onboarding_v2', 'new_checkout']), experimentFilter: new Set(['pricing_experiment']), layerFilter: new Set(['ui_layer']), }); res.json({ statsigValues: values }); }); ``` -------------------------------- ### Install the SDK Source: https://docs.statsig.com/server-core/dotnetCoreSDK Instructions for installing the Statsig .NET SDK using the NuGet package manager. ```APIDOC ## Installation ``` dotnet add package Statsig.Dotnet ``` Or add the package reference to your `.csproj` file: ``` ``` ``` -------------------------------- ### Full Code Example: Server and Client Integration Source: https://docs.statsig.com/server-core/python-core Demonstrates a complete example of generating a client initialize response on the server using Flask and initializing the client SDK with these values. ```APIDOC ## Full Code Example: Server and Client Integration ### Description This example shows how to use the `get_client_initialize_response` method on the server-side (using Flask) to generate bootstrap data, and then how a client-side JavaScript application can use this data to initialize the Statsig SDK, reducing initial network requests. ### Server-Side (Python/Flask) ```python theme={null} # Server-side code import json from statsig_python_core import Statsig, StatsigUser, StatsigOptions from flask import Flask, request, jsonify app = Flask(__name__) # Initialize the server SDK (replace with your actual server secret key) options = StatsigOptions() statsig = Statsig('server-secret-key', options) statsig.initialize().wait() # API endpoint to provide bootstrap values @app.route('/statsig-bootstrap') def statsig_bootstrap(): # Create a user object from the request parameters user = StatsigUser( user_id=request.args.get('userID', ''), email=request.args.get('email'), ip=request.remote_addr, user_agent=request.headers.get('User-Agent') ) # Generate the client initialize response response_data = statsig.get_client_initialize_response( user, hash='djb2', # Example: using djb2 hashing client_sdk_key='client-key' # Example: filtering by client SDK key ) # Parse the JSON response statsig_values = json.loads(response_data) # Return the values to the client return jsonify({'statsigValues': statsig_values}) # To run this Flask app: # 1. Save as app.py # 2. Run: flask --app app run ``` ### Client-Side (@statsig/js-client) ```javascript theme={null} // Client-side code using @statsig/js-client import { Statsig } from '@statsig/js-client'; async function initializeStatsigClient() { // Fetch bootstrap values from your server API const response = await fetch('/statsig-bootstrap?userID=some_user_id&email=user@example.com'); const { statsigValues } = await response.json(); // Initialize the client SDK with the bootstrap values await Statsig.initialize({ sdkKey: 'client-sdk-key', // Must match the key used on the server if filtering initializeValues: statsigValues, }); console.log('Statsig client initialized with bootstrap values.'); } initializeStatsigClient(); ``` ``` -------------------------------- ### Install Legacy Node SDK Source: https://docs.statsig.com/server-core/migration-guides/node Install the legacy Node JS SDK using npm. ```bash npm install statsig-node ``` -------------------------------- ### Install Legacy Python SDK Source: https://docs.statsig.com/server-core/migration-guides/python Install the legacy Python SDK using pip. ```bash pip install statsig ``` -------------------------------- ### Install Statsig Java SDK Core Library (Gradle) Source: https://docs.statsig.com/server-core/java-core Install the platform-independent core library. This is the first step in the advanced two-part installation process. ```groovy repositories { mavenCentral() } dependencies { implementation 'com.statsig:javacore:X.X.X' // Replace X.X.X with the latest version } ``` -------------------------------- ### Install Node Core SDK Source: https://docs.statsig.com/server-core/migration-guides/node Install the new Node JS Core SDK using npm. ```bash npm install @statsig/statsig-node-core ``` -------------------------------- ### Manually Start Session Recording with SDK Key Source: https://docs.statsig.com/session-replay/configure Start a session recording by importing and calling the startRecording function with your client SDK key. This method also respects global targeting gates and sampling rates. ```javascript import { startRecording } from '@Statsig/session-replay'; … startRecording(CLIENT_SDK_KEY) ``` -------------------------------- ### Install Statsig Node.js SDK Source: https://docs.statsig.com/server/nodejsServerSDK Install the Statsig Node.js SDK using NPM or Yarn. ```bash npm install statsig-node ``` ```bash yarn add statsig-node ``` -------------------------------- ### Next.js Instrumentation Setup for Logs with Pino Source: https://docs.statsig.com/infra-analytics/getting-started Extend the OpenTelemetry Node.js SDK configuration to include log record processors and Pino instrumentation for exporting logs to Statsig. This example assumes trace and metric configurations are already in place. ```typescript // instrumentation.ts (continued) import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'; const statsigKey = process.env.STATSIG_SERVER_SDK_SECRET; const headers = { 'statsig-api-key': statsigKey ?? '' }; const sdk = new NodeSDK({ // ... other config ... logRecordProcessors: [ new BatchLogRecordProcessor( new OTLPLogExporter({ url: 'https://api.statsig.com/otlp/v1/logs', // or // url: /v1/logs headers }) ), ], instrumentations: [getNodeAutoInstrumentations(), new PinoInstrumentation()], }); // in your application code, e.g., app.ts import pino from 'pino'; const logger = pino(); logger.info('OTel logs initialized'); ``` -------------------------------- ### Install Go OpenTelemetry Packages Source: https://docs.statsig.com/infra-analytics/send-traces Install the necessary OpenTelemetry packages for Go to enable trace export. ```bash go get go.opentelemetry.io/otel/sdk go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp go.opentelemetry.io/otel/semconv/v1.26.0 ``` -------------------------------- ### Install Node AI SDK with npm Source: https://docs.statsig.com/ai-evals/node Install the Statsig AI Node SDK using npm. This command also installs the Node Server SDK if it's not already present. ```bash npm install @statsig/statsig-ai ``` -------------------------------- ### Basic CLI Session Replay Usage Source: https://docs.statsig.com/session-replay/cli-session-replay Initialize the StatsigClient with the CLI session replay plugin and ensure logging is enabled for CLI environments. This code demonstrates the basic setup required to start recording. ```javascript import { StatsigClient } from '@statsig/js-client'; import { StatsigCliSessionReplayPlugin } from '@statsig/cli-session-replay-node'; const client = new StatsigClient( 'your-client-key', { userID: 'user-123' }, { loggingEnabled: 'always', // Required for CLI environments plugins: [new StatsigCliSessionReplayPlugin()], } ); // Recording starts here console.log('Hello from CLI!'); await client.initializeAsync(); // Your CLI application logic here console.log('Continue'); ``` -------------------------------- ### Install OpenSSL Development Libraries Source: https://docs.statsig.com/server-core/node-core Run this command to update package lists and install the OpenSSL development libraries, which may resolve SSL-related installation errors. ```shell apt-get update && apt-get install libcurl4-openssl-dev -y && rm -rf /var/lib/apt/lists/* ``` -------------------------------- ### Install SDK with yarn Source: https://docs.statsig.com/client/javascript-sdk Install the Statsig Web SDK and optional packages for Session Replay or Auto Capture using yarn. ```bash yarn add @statsig/js-client @statsig/session-replay @statsig/web-analytics ``` -------------------------------- ### Install SDK with npm Source: https://docs.statsig.com/client/javascript-sdk Install the Statsig Web SDK and optional packages for Session Replay or Auto Capture using npm. ```bash npm install @statsig/js-client @statsig/session-replay @statsig/web-analytics ``` -------------------------------- ### Install Node AI SDK with yarn Source: https://docs.statsig.com/ai-evals/node Install the Statsig AI Node SDK using yarn. This command also installs the Node Server SDK if it's not already present. ```bash yarn add @statsig/statsig-ai ``` -------------------------------- ### Install Skill Globally Source: https://docs.statsig.com/integrations/agent-skills Install a specific skill from the repository globally for your user account using the '-g' flag and specifying the skill name. ```bash npx skills add -g statsig-io/agent-skills --skill statsig-dashboard ``` -------------------------------- ### Install Node AI SDK with pnpm Source: https://docs.statsig.com/ai-evals/node Install the Statsig AI Node SDK using pnpm. This command also installs the Node Server SDK if it's not already present. ```bash pnpm add @statsig/statsig-ai ``` -------------------------------- ### Install Statsig Serverless SDK Source: https://docs.statsig.com/integrations/cloudflare Install the Statsig serverless SDK for Node.js. This is a prerequisite for using the Cloudflare integration. ```bash npm install @statsig/serverless-client ``` -------------------------------- ### Example Data Adapter Implementation in Go Source: https://docs.statsig.com/server/golangSDK Provides a basic in-memory implementation of the `IDataAdapter` interface using a map and a mutex for thread safety. This example sets `ShouldBeUsedForQueryingUpdates` to false, meaning it will not poll for updates. ```go type dataAdapterExample struct { store map[string]string mu sync.RWMutex } func (d *dataAdapterExample) Get(key string) string { d.mu.RLock() defer d.mu.RUnlock() return d.store[key] } func (d *dataAdapterExample) Set(key string, value string) { d.mu.Lock() defer d.mu.Unlock() d.store[key] = value } func (d *dataAdapterExample) Initialize() {} func (d *dataAdapterExample) Shutdown() {} func (d *dataAdapterExample) ShouldBeUsedForQueryingUpdates(key string) bool { return false } ``` -------------------------------- ### Install OpenAI and Statsig Packages Source: https://docs.statsig.com/integrations/openai Install the necessary Python packages for OpenAI and Statsig integration. ```bash pip3 install openai, statsig ``` -------------------------------- ### Install Statsig .NET SDK Source: https://docs.statsig.com/server-core/dotnetCoreSDK Install the Statsig .NET SDK using the dotnet CLI or by adding a package reference to your .csproj file. Ensure you are using .NET 8.0 or later. ```bash dotnet add package Statsig.Dotnet ``` ```xml ``` -------------------------------- ### Get Experiment Details via OpenAPI Source: https://docs.statsig.com/api-reference/experiments/get-experiment This OpenAPI definition describes the GET endpoint for retrieving a specific experiment by its ID. It outlines the request parameters, response structure, and example payloads. ```yaml https://api.statsig.com/openapi/20240601.json get /console/v1/experiments/{id} openapi: 3.0.0 info: title: Console API description: >- The "Console API" is the CRUD API for performing the actions offered on console.statsig.com without needing to go through the web UI. If you have any feature requests, drop on in to our [slack channel](https://www.statsig.com/slack) and let us know.

Authorization
All requests must include the **STATSIG-API-KEY** field in the header. The value should be a **Console API Key** which can be created in the Project Settings on [console.statsig.com/api_keys](https://console.statsig.com/api_keys)

Rate Limiting
Requests to the Console API are limited to ~ 100reqs / 10secs and ~ 900reqs / 15 mins.

Keyboard Search
Use Ctrl/Cmd + K to search for specific endpoints. version: 20240601.0.0 contact: {} servers: - url: https://statsigapi.net security: [] tags: [] paths: /console/v1/experiments/{id}: get: tags: - Experiments - Experiments summary: Get Experiment parameters: - name: id required: true in: path description: id schema: type: string responses: '200': description: Get Experiment Success content: application/json: schema: allOf: - $ref: '#/components/schemas/SingleDataResponse' - properties: data: $ref: '#/components/schemas/ExternalExperimentDto' example: message: Experiments listed successfully. data: id: a_experiment permalink: >- https://console.statsig.com/company_id/experiments/a_experiment description: '' lastModifiedTime: 1707427635442 lastModifierEmail: null createdTime: 1707427634717 creatorName: CONSOLE API lastModifierName: CONSOLE API lastModifierID: 4FKF0sUbi1D7xZFW5vcHWB idType: userID status: setup experimentType: BASE launchedGroupID: null layerID: statsig::a_experiment_layer hypothesis: '' primaryMetrics: [] primaryMetricTags: [] secondaryMetrics: [] secondaryMetricTags: [] startTime: null endTime: null decisionTime: null groups: - name: Control id: 4HbgLdfqlIeN3sHkyMG1qC size: 50 parameterValues: {} - name: Test size: 50 parameterValues: {} allocation: 100 duration: 14 targetingGateID: '' defaultConfidenceInterval: '95' bonferroniCorrection: false tags: - '* Core' decisionReason: '' owner: ownerType: USER ownerName: Test User healthCheckStatus: PASSED isStale: false inlineTargetingRulesJSON: '{}' example: message: Experiments listed successfully. data: id: a_experiment permalink: >- https://console.statsig.com/company_id/experiments/a_experiment description: '' lastModifiedTime: 1707427635442 lastModifierEmail: null createdTime: 1707427634717 creatorName: CONSOLE API lastModifierName: CONSOLE API lastModifierID: 4FKF0sUbi1D7xZFW5vcHWB idType: userID status: setup experimentType: BASE launchedGroupID: null layerID: statsig::a_experiment_layer hypothesis: '' primaryMetrics: [] primaryMetricTags: [] secondaryMetrics: [] secondaryMetricTags: [] startTime: null endTime: null decisionTime: null groups: - name: Control id: 4HbgLdfqlIeN3sHkyMG1qC size: 50 ``` -------------------------------- ### Install the Statsig JS On-Device Evaluation Client Source: https://docs.statsig.com/client/js-on-device-eval-client Install the Statsig SDK using npm. Ensure you have the correct package name for on-device evaluation. ```bash npm install @statsig/js-on-device-eval-client ``` -------------------------------- ### Get Dynamic Config Rules OpenAPI Specification Source: https://docs.statsig.com/api-reference/dynamic-configs/get-dynamic-config-rules This OpenAPI specification defines the GET endpoint for retrieving dynamic configuration rules. It outlines the request parameters, response structure, and example data. ```yaml openapi: 3.0.0 info: title: Console API description: >- The "Console API" is the CRUD API for performing the actions offered on console.statsig.com without needing to go through the web UI. If you have any feature requests, drop on in to our [slack channel](https://www.statsig.com/slack) and let us know.

Authorization
All requests must include the **STATSIG-API-KEY** field in the header. The value should be a **Console API Key** which can be created in the Project Settings on [console.statsig.com/api_keys](https://console.statsig.com/api_keys)

Rate Limiting
Requests to the Console API are limited to ~ 100reqs / 10secs and ~ 900reqs / 15 mins.

Keyboard Search
Use Ctrl/Cmd + K to search for specific endpoints. version: 20240601.0.0 contact: {} servers: - url: https://statsigapi.net security: [] tags: [] paths: /console/v1/dynamic_configs/{id}/rules: get: tags: - Dynamic Configs summary: Get Dynamic Config Rules parameters: - name: id required: true in: path description: id schema: type: string responses: '200': description: Get Dynamic Config Rules Response content: application/json: schema: allOf: - $ref: '#/components/schemas/PaginationResponseWithMessage' - properties: data: type: array items: $ref: '#/components/schemas/DynamicConfigRulesDto' example: message: Dynamic Config rules read successfully. data: - rules: - id: 5pjzfmF8KLFsh81kBPyxvR baseID: 5pjzfmF8KLFsh81kBPyxvR name: rule name passPercentage: 1 conditions: - type: browser_name targetValue: [] operator: any environments: null completedAutomatedRollouts: [] pendingAutomatedRollouts: [] - id: 6jQEnu1fCnXqjXhm1qGEnt baseID: 6jQEnu1fCnXqjXhm1qGEnt name: Other2 passPercentage: 80 conditions: [] environments: null completedAutomatedRollouts: [] pendingAutomatedRollouts: [] - id: 4DonExIcOjSV8kG3WSQ5Zm baseID: 4DonExIcOjSV8kG3WSQ5Zm name: Austin's fav rule passPercentage: 8 conditions: [] environments: null completedAutomatedRollouts: [] pendingAutomatedRollouts: [] pagination: itemsPerPage: 20000 pageNumber: 1 totalItems: 1 nextPage: null previousPage: null all: '' example: message: Dynamic Config rules read successfully. data: - rules: - id: 5pjzfmF8KLFsh81kBPyxvR baseID: 5pjzfmF8KLFsh81kBPyxvR name: rule name passPercentage: 1 conditions: - type: browser_name targetValue: [] operator: any environments: null completedAutomatedRollouts: [] pendingAutomatedRollouts: [] - id: 6jQEnu1fCnXqjXhm1qGEnt baseID: 6jQEnu1fCnXqjXhm1qGEnt name: Other2 passPercentage: 80 conditions: [] environments: null completedAutomatedRollouts: [] pendingAutomatedRollouts: [] - id: 4DonExIcOjSV8kG3WSQ5Zm baseID: 4DonExIcOjSV8kG3WSQ5Zm name: Austin's fav rule passPercentage: 8 conditions: [] environments: null completedAutomatedRollouts: [] ``` -------------------------------- ### Integrate Statsig AI Tracing with Existing Node.js OTel Setup Source: https://docs.statsig.com/ai-evals/node When you have an existing OpenTelemetry Node.js SDK setup, use `initializeTracing` to get the Statsig processor. Ensure this processor is included in your `NodeSDK`'s `spanProcessors` to export spans to Statsig. ```js // instrumentation.{js,ts} import { NodeSDK } from '@opentelemetry/sdk-node'; import { PeriodicExportingMetricReader, ConsoleMetricExporter, } from '@opentelemetry/sdk-metrics'; import { initializeTracing } from '@statsig/statsig-ai/otel'; // when you have your own otel setup and don't want to use the global trace provider // you can disable it with the options below const { processor } = initializeTracing({ // prevents creating a global context manager skipGlobalContextManagerSetup: true, exporterOptions: { sdkKey: process.env.STATSIG_SDK_KEY!, }, }); const sdk = new NodeSDK({ // IMPORTANT: use the processor created by initializeTracing // to make sure that spans are exported to Statsig spanProcessors: [processor], metricReader: new PeriodicExportingMetricReader({ exporter: new ConsoleMetricExporter(), }), // ... other node sdk options like autoInstrumentations }); sdk.start(); export { sdk }; ``` -------------------------------- ### OpenAPI Specification for Get Teams Settings Source: https://docs.statsig.com/api-reference/settings/get-teams-settings This OpenAPI specification defines the GET endpoint for retrieving team settings. It includes request parameters, response schemas, and example payloads for success and error cases. Ensure you include your STATSIG-API-KEY in the header for authentication. ```yaml openapi: 3.0.0 info: title: Console API description: >- The "Console API" is the CRUD API for performing the actions offered on console.statsig.com without needing to go through the web UI. If you have any feature requests, drop on in to our [slack channel](https://www.statsig.com/slack) and let us know.

Authorization
All requests must include the **STATSIG-API-KEY** field in the header. The value should be a **Console API Key** which can be created in the Project Settings on [console.statsig.com/api_keys](https://console.statsig.com/api_keys)

Rate Limiting
Requests to the Console API are limited to ~ 100reqs / 10secs and ~ 900reqs / 15 mins.

Keyboard Search
Use Ctrl/Cmd + K to search for specific endpoints. version: 20240601.0.0 contact: {} servers: - url: https://statsigapi.net security: [] tags: [] paths: /console/v1/settings/teams: get: tags: - Settings summary: Get Teams Settings parameters: [] responses: '200': description: Get Teams Settings Response content: application/json: schema: allOf: - $ref: '#/components/schemas/SingleDataResponse' - properties: data: $ref: '#/components/schemas/SettingsTeamsContractDto' example: message: Settings read successfully. data: require_teams_on_configs: true example: message: Settings read successfully. data: require_teams_on_configs: true '400': description: Invalid request. Please check the request input and try again. content: application/json: schema: type: object properties: status: type: integer enum: - 400 message: type: string required: - status - message examples: Invalid Request: value: status: 400 message: >- Invalid request. Please check the request input and try again. '401': description: >- This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx content: application/json: schema: type: object properties: status: type: integer enum: - 401 message: type: string required: - status - message examples: Invalid Endpoint: value: status: 401 message: >- This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx security: - STATSIG-API-KEY: [] components: schemas: SingleDataResponse: type: object properties: message: type: string description: A simple string explaining the result of the operation. data: type: object description: A single result. required: - message - data SettingsTeamsContractDto: type: object properties: require_teams_on_configs: type: boolean description: Whether a team is required on each new config. required: - require_teams_on_configs securitySchemes: STATSIG-API-KEY: type: apiKey name: STATSIG-API-KEY in: header ``` -------------------------------- ### Serverless Function Example Source: https://docs.statsig.com/integrations/serverless An example of a serverless function demonstrating initialization, gate checking, event logging, and flushing using the Statsig Serverless SDK. ```javascript import { StatsigServerlessClient } from '@statsig/serverless-client'; export default async function handler(request) { const client = new StatsigServerlessClient(process.env.STATSIG_KEY); let init = await client.initializeAsync(); const user = { userID: Math.random().toString().substring(2, 5) }; const passed = client.checkGate('pass_gate', user); client.logEvent('serverless_event', user, passed.toString()); client.flush(); return new Response( JSON.stringify({ passed, user }), ); } ``` -------------------------------- ### Initialize Statsig SDK with Options Source: https://docs.statsig.com/server-core/java-core Initialize the Statsig SDK with optional configurations. This example demonstrates how to build StatsigOptions, which can be used for automatic platform detection. ```java import com.statsig.*; // All StatsigOptions are optional, feel free to adjust them as needed StatsigOptions options = new StatsigOptions.Builder().build(); Statsig statsig = new Statsig("your-secret-key", options); ``` -------------------------------- ### Get Pulse Load History Details (Warehouse Native) Source: https://docs.statsig.com/llms.txt Retrieves detailed historical load information for Pulse, specifically for warehouse-native setups. ```APIDOC ## Get Pulse Load History Details (Warehouse Native) ### Description Retrieves detailed historical load information for Pulse in a warehouse-native environment. ### Method GET ### Endpoint `/v1/pulse/load_history/details` ### Parameters #### Query Parameters - **start_time** (integer) - Optional - Unix timestamp for the start of the period. - **end_time** (integer) - Optional - Unix timestamp for the end of the period. ### Request Body (No request body) ### Response #### Success Response (200) - **details** (array) - An array of detailed load history entries. #### Response Example ```json { "details": [ {"timestamp": 1678886400, "load_ms": 500, "records_processed": 10000}, {"timestamp": 1678886460, "load_ms": 550, "records_processed": 10500} ] } ``` ``` -------------------------------- ### Install React Bindings via npm Source: https://docs.statsig.com/session-replay/install Install the Statsig packages for React applications, including session replay and web analytics, using npm. ```bash npm install @statsig/session-replay @statsig/web-analytics @statsig/react-bindings ``` -------------------------------- ### Initialize SDK with Bootstrap Values Source: https://docs.statsig.com/sdks/debugging Demonstrates how to correctly bootstrap a client SDK with values generated for a specific user on the server. Ensure the user object used for bootstrapping on the server exactly matches the user object initialized on the client to prevent `InvalidBootstrap` errors. ```javascript // Server side const userA = { userID: 'user-a' }; const bootstrapValues = Statsig.getClientInitializeResponse(userA); // Client side const bootstrapValues = await fetchStatsigValuesFromMyServers(); const userB = { userID: 'user-b' }; // <-- Different from userA await Statsig.initialize('client-key', userB, { initializeValues: bootstrapValues }); ``` -------------------------------- ### OpenAPI Specification for SCIM Groups Source: https://docs.statsig.com/api-reference/scim-groups/get-scimgroups This OpenAPI specification defines the GET endpoint for retrieving SCIM groups. It includes parameters for filtering, starting index, and count. ```yaml openapi: 3.0.0 info: title: SCIM API description: | APIs for SCIM compliance. version: '1.0' contact: {} servers: - url: https://statsigapi.net security: [] tags: [] paths: /scim/Groups: get: tags: - SCIM Groups operationId: GroupsController_genListGroups parameters: - name: filter required: false in: query schema: type: string - name: startIndex required: false in: query schema: oneOf: - type: string - type: number - name: count required: false in: query schema: oneOf: - type: string - type: number responses: '200': description: '' ``` -------------------------------- ### Statsig Initialization with Options Source: https://docs.statsig.com/server/pythonSDK Demonstrates how to initialize the Statsig SDK with custom options, such as setting the environment tier. ```APIDOC ## Initialize Statsig with Options ### Description Initializes the Statsig SDK with a secret key and optional `StatsigOptions` to customize behavior. ### Method `statsig.initialize(secret_key, options)` ### Parameters - `secret_key` (str): Your Statsig API key. - `options` (StatsigOptions): An optional object to configure SDK behavior. - `tier` (StatsigEnvironmentTier | str): Sets the environment tier. - `timeout` (int): Enforces a minimum timeout on network requests. - `init_timeout` (int): Sets the maximum timeout for initialization network requests. - `rulesets_sync_interval` (int): How often the SDK updates rulesets. - `idlists_sync_interval` (int): How often the SDK updates ID lists. - `local_mode` (bool): Disables all network requests for testing. - `bootstrap_values` (str): String to bootstrap SDK values. - `rules_updated_callback` (typing.Callable): Callback for rules updates. - `event_queue_size` (int): Number of events to batch before flushing. - `data_store` (IDataStore): Custom data store for config specs. - `proxy_configs` (Optional[Dict[NetworkEndpoint, ProxyConfig]]): Network proxy configurations. - `fallback_to_statsig_api` (Optional[bool]): Fallback to Statsig CDN if overridden API fails. - `initialize_sources` (Optional[List[DataSource]]): List of sources for initialization. - `config_sync_sources` (Optional[List[DataSource]]): List of sources for config sync. ### Request Example ```python from statsig import statsig, StatsigEnvironmentTier, StatsigOptions options = StatsigOptions(None, StatsigEnvironmentTier.development) statsig.initialize("secret-key", options).wait() ``` ### Setting Environment Parameters Environment parameters can also be set using `set_environment_parameter` on the `StatsigOptions` object. ### Request Example ```python from statsig import statsig, StatsigEnvironmentTier, StatsigOptions options = StatsigOptions() options.set_environment_parameter("tier", StatsigEnvironmentTier.development.value) statsig.initialize("secret-key", options).wait() ``` ``` -------------------------------- ### SCIM Users API Specification (OpenAPI) Source: https://docs.statsig.com/api-reference/scim-users/get-scimusers This OpenAPI specification defines the GET endpoint for retrieving SCIM users. It includes parameters for filtering, starting index, and count. ```yaml openapi: 3.0.0 info: title: SCIM API description: | APIs for SCIM compliance. version: '1.0' contact: {} servers: - url: https://statsigapi.net security: [] tags: [] paths: /scim/Users: get: tags: - SCIM Users operationId: UserController_genListUsers parameters: - name: filter required: false in: query schema: type: string - name: startIndex required: false in: query schema: oneOf: - type: string - type: number - name: count required: false in: query schema: oneOf: - type: string - type: number responses: '200': description: '' ``` -------------------------------- ### Manually Start Session Recording with Client Instance Source: https://docs.statsig.com/session-replay/configure Initiate a session recording on demand using the startRecording method on a SessionReplay client instance. This respects global targeting gates and sampling rates. ```javascript const sessionReplayClient = new SessionReplay(client); … if (someCondition) { sessionReplayClient.startRecording(); } ``` -------------------------------- ### Example User Persistent Storage Implementation Source: https://docs.statsig.com/server/nodejsServerSDK An example implementation of the `IUserPersistentStorage` interface using a simple in-memory object store. ```typescript class UserPersistentStorageExample implements IUserPersistentStorage { public store: Record = {}; load(key: string): UserPersistedValues { return this.store[key]; } save(key: string, configName: string, data: StickyValues): void { if (!(key in this.store)) { this.store[key] = {}; } this.store[key][configName] = data; } delete(key: string, configName: string): void { delete this.store[key][configName]; } } ``` -------------------------------- ### Install Statsig React SDK Source: https://docs.statsig.com/guides/check-gate Install the Statsig React SDK using npm. This is the first step to integrating Statsig into your React application. ```bash npm install @statsig/react ``` -------------------------------- ### Get Usage Report Source: https://docs.statsig.com/api-reference/usage/get-report-in-csv-format Retrieve a usage report in CSV format by specifying a time range. The `end` parameter is required, while `start` is optional. The report will be returned as a CSV file. ```APIDOC ## GET /console/v1/project/usage_billing/report ### Description Fetches a usage report in CSV format for a specified time range. The `end` parameter is mandatory, and the `start` parameter is optional. The response content type is `text/csv`. ### Method GET ### Endpoint /console/v1/project/usage_billing/report ### Parameters #### Query Parameters - **start** (integer) - Optional - Unix timestamp in ms - **end** (integer) - Required - Unix timestamp in ms ### Response #### Success Response (200) - **(binary)** - The generated report as a CSV file. #### Error Response (400) - **status** (integer) - 400 - **message** (string) - Error message indicating invalid request. #### Error Response (401) - **status** (integer) - 401 - **message** (string) - Error message indicating an invalid API key. ``` -------------------------------- ### Initialize OpenAI and Statsig SDKs Source: https://docs.statsig.com/integrations/openai Set up the necessary API keys and initialize the Statsig SDK. This is a prerequisite for using Statsig features and making OpenAI API calls. ```python import openai from statsig import statsig, StatsigEvent, StatsigUser import time openai.api_key = "your_openai_key" statsig.initialize("your_statsig_secret") user = StatsigUser("user-id") #This is a placeholder ID - in a normal experiment Statsig recommends using a user's actual unique ID for consistency in targeting. See https://docs.statsig.com/concepts/user ``` -------------------------------- ### Install Pino and OpenTelemetry Pino Instrumentation Source: https://docs.statsig.com/infra-analytics/getting-started Install the pino logger and its OpenTelemetry instrumentation package to enable automatic log collection. ```bash npm i pino @opentelemetry/instrumentation-pino ``` -------------------------------- ### Install Statsig Node Core Source: https://docs.statsig.com/sdks/quickstart Install the Statsig Node.js SDK using npm. This command adds the necessary package to your project. ```bash npm i @statsig/statsig-node-core ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.