### Initialize Application Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/05-app-lifecycle.md The `Setup` method initializes the application by starting CPU profiling, determining the version, and initializing features. It should be called during application startup. ```go func (a *app) Setup() ``` -------------------------------- ### Setup Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/05-app-lifecycle.md Initializes the application by starting CPU profiling, determining the version, and initializing features. This method should be called during application startup. ```APIDOC ## Setup ### Description Initializes the application. This includes starting CPU profiling if configured, determining the version (open-source vs. enterprise), and initializing features. It is called during application startup before any workers begin. ### Signature ```go func (a *app) Setup() ``` ### Parameters This method does not take any parameters. ``` -------------------------------- ### Gateway Setup Method Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/02-gateway-api.md Initializes the gateway with all necessary dependencies. This method must be called before starting the web handler. ```go func (gw *Handle) Setup( ctx context.Context, config *config.Config, logger logger.Logger, stat stats.Stats, application app.App, backendConfig backendconfig.BackendConfig, jobsDB jobsdb.JobsDB, rateLimiter throttler.Throttler, versionHandler func(w http.ResponseWriter, r *http.Request), rsourcesService rsources.JobService, transformerFeaturesService transformer.FeaturesService, sourcehandle sourcedebugger.SourceDebugger, streamMsgValidator func(message *stream.Message) error, opts ...OptFunc, ) error ``` -------------------------------- ### CPU Profiling Setup Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/05-app-lifecycle.md CPU profiling starts automatically in Setup() if the Cpuprofile option is set, writing profiling data to a specified file. It stops in the Stop() method. Analyze with: go tool pprof profile.out ```text Analyze with: `go tool pprof profile.out` ``` -------------------------------- ### File-Based Configuration Example Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/04-backend-config-api.md Example JSON structure for loading RudderStack configuration from a file. ```json { "workspaceId": { "sources": [...], "destinations": [...], ... } } ``` -------------------------------- ### Rust SDK Extract Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Basic example for using the Rust SDK to call the extract method. Requires context setup and handles the result. ```rust extern crate InternalAPIApi; pub fn main() { let mut context = InternalAPIApi::Context::default(); let result = client.extract(&context).wait(); println!("{:?}", result); } ``` -------------------------------- ### PHP API Client Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Demonstrates how to use the PHP SDK to interact with the HTTP API, including authentication and making a 'page' call. Ensure you have the SDK installed via Composer. ```php setUsername('YOUR_USERNAME'); OpenAPITools Client Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); // Create an instance of the API class $api_instance = new OpenAPITools Client Api HTTPAPIApi(); $pagePayload = ; // PagePayload | try { $result = $api_instance->page($pagePayload); print_r($result); } catch (Exception $e) { echo 'Exception when calling HTTPAPIApi->page: ', $e->getMessage(), PHP_EOL; } ?> ``` -------------------------------- ### Full config.yaml Example Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/07-configuration-reference.md This is a comprehensive example of the config.yaml file, illustrating various configuration options for different RudderStack components. ```yaml CONFIG_BACKEND_URL: https://api.rudderstack.com CP_ROUTER_URL: https://cp-router.rudderlabs.com BackendConfig: configFromFile: false configJSONPath: /etc/rudderstack/workspaceConfig.json pollInterval: 5s envReplacementEnabled: true Gateway: webPort: 8080 maxReqSizeInKB: 4000 maxUserWebRequestWorkerProcess: 64 maxDBWriterProcess: 256 maxUserRequestBatchSize: 128 maxDBBatchSize: 128 userWebRequestBatchTimeout: 15ms dbBatchWriteTimeout: 5ms enableRateLimit: false enableSuppressUserFeature: true maxConcurrentRequests: 50000 webhookV2HandlerEnabled: false Processor: jobQueryBatchSize: 100000 updateStatusBatchSize: 1000 readSleep: 1s maxReadSleep: 10s num: 8 Router: jobQueryBatchSize: 100000 updateStatusBatchSize: 1000 readSleep: 1s maxReadSleep: 10s num: 8 minRetryBackoff: 1s maxRetryBackoff: 1h jobsdb: maxTableSize: 100000000 cacheExpiration: 5m addNewDSLoopSleepDuration: 1s ReadTimeout: 0s WriteTimeout: 10s IdleTimeout: 720s MaxHeaderBytes: 524288 ``` -------------------------------- ### Setup Backend Configuration System Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/04-backend-config-api.md Initializes the backend configuration system. Requires a configuration environment handler. ```go func Setup(configEnvHandler *configenv.ConfigEnvHandler) error ``` -------------------------------- ### Handle.Setup Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/02-gateway-api.md Initializes the gateway with necessary dependencies and configurations. This method must be called before starting the web handler. ```APIDOC ### Setup ```go func (gw *Handle) Setup( ctx context.Context, config *config.Config, logger logger.Logger, stat stats.Stats, application app.App, backendConfig backendconfig.BackendConfig, jobsDB jobsdb.JobsDB, rateLimiter throttler.Throttler, versionHandler func(w http.ResponseWriter, r *http.Request), rsourcesService rsources.JobService, transformerFeaturesService transformer.FeaturesService, sourcehandle sourcedebugger.SourceDebugger, streamMsgValidator func(message *stream.Message) error, opts ...OptFunc, ) error ``` Initializes the gateway with dependencies. Must be called before `StartWebHandler`. **Parameters**: - `ctx`: Context for background operations - `config`: Configuration manager - `logger`: Logging instance - `stat`: Statistics collector - `application`: App features (suppression, reporting, etc.) - `backendConfig`: Backend configuration provider - `jobsDB`: Jobs database instance - `rateLimiter`: Rate limiting implementation - `versionHandler`: Handler for /version endpoint - `rsourcesService`: RudderSources job service - `transformerFeaturesService`: Transformer feature flags - `sourcehandle`: Source debugger - `streamMsgValidator`: Stream message validator - `opts`: Optional configuration functions **Returns**: Error if setup fails ``` -------------------------------- ### Setup Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/04-backend-config-api.md Initializes the backend configuration system. It requires a configuration environment handler to set up the system. ```APIDOC ## Setup ### Description Initializes backend config system with configuration environment handler. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (0) Returns nil on success. #### Response Example None ERROR HANDLING: - Returns an error if setup fails. ``` -------------------------------- ### Example Metric with Configuration Tags Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/09-runner-initialization.md An example of a metric with configuration tags including version, commit, build date, and builder. ```text rudder_server_config{version="1.2.3",commit="abc123",buildDate="2024-06-24",builtBy="github-actions"} 1 ``` -------------------------------- ### Rust Batch API Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of using the Rust SDK to send a batch payload. Authentication context needs to be set up. ```rust extern crate HTTPAPIApi; pub fn main() { let batchPayload = ; // BatchPayload let mut context = HTTPAPIApi::Context::default(); let result = client.batch(batchPayload, &context).wait(); println!("{:?}", result); } ``` -------------------------------- ### C# HTTP API Screen Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Demonstrates how to configure basic authentication and call the screen method with a ScreenPayload in C#. ```csharp using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; namespace Example { public class screenExample { public void main() { // Configure HTTP basic authorization: writeKeyAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; // Create an instance of the API class var apiInstance = new HTTPAPIApi(); var screenPayload = new ScreenPayload(); // ScreenPayload | try { // Screen 'String' result = apiInstance.screen(screenPayload); Debug.WriteLine(result); } catch (Exception e) { Debug.Print("Exception when calling HTTPAPIApi.screen: " + e.Message ); } } } } ``` -------------------------------- ### Dart SDK Replay Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Shows how to call the replay method using the Dart SDK. This example assumes the DefaultApi instance is already configured. ```dart import 'package:openapi/api.dart'; final api_instance = DefaultApi(); try { final result = await api_instance.replay(); print(result); } catch (e) { print('Exception when calling DefaultApi->replay: $e\n'); } ``` -------------------------------- ### StartWithIDs Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/04-backend-config-api.md Starts the process of fetching configuration specifically for a given set of workspaces. If no IDs are provided, it fetches for all workspaces. ```APIDOC ## StartWithIDs ### Description Starts configuration fetching for specific workspaces. ### Method POST ### Endpoint /config/start ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **workspaces** (string): Comma-separated workspace IDs (empty for all) ### Request Example { "workspaces": "workspace1,workspace2" } ### Response #### Success Response (200) No content, indicates configuration fetching has started. #### Response Example None ERROR HANDLING: - Returns an error if starting configuration fetching fails. ``` -------------------------------- ### Rust Group API Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html A basic example of using the group API in Rust. Requires setting up the API context. ```rust extern crate HTTPAPIApi; pub fn main() { let groupPayload = ; // GroupPayload let mut context = HTTPAPIApi::Context::default(); let result = client.group(groupPayload, &context).wait(); println!("{:?}", result); } ``` -------------------------------- ### Get Current Time and Parse/Format Dates Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/10-utilities-and-patterns.md Demonstrates how to get the current time (which can be mocked for testing) and parse/format date strings using flexible formats. ```go import "github.com/rudderlabs/rudder-server/utils/timeutil" // Current time (mockable for testing) now := timeutil.Now() // Parse time with flexible format t, _ := dateparse.ParseAny(dateString) // Format time formatted := now.Format(time.RFC3339) ``` -------------------------------- ### ConfigEnv Feature Setup Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/05-app-lifecycle.md Sets up the ConfigEnv feature, which handles environment variable substitution within the application's configuration. ```go configEnvHandler := app.Features().ConfigEnv.Setup() ``` -------------------------------- ### Java Alias Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to make an alias call using the Java SDK. Configure HTTP basic authorization with your username and password. ```java import org.openapitools.client.*; import org.openapitools.client.auth.*; import org.openapitools.client.model.*; import org.openapitools.client.api.HTTPAPIApi; import java.io.File; import java.util.*; public class HTTPAPIApiExample { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); // Configure HTTP basic authorization: writeKeyAuth HttpBasicAuth writeKeyAuth = (HttpBasicAuth) defaultClient.getAuthentication("writeKeyAuth"); writeKeyAuth.setUsername("YOUR USERNAME"); writeKeyAuth.setPassword("YOUR PASSWORD"); // Create an instance of the API class HTTPAPIApi apiInstance = new HTTPAPIApi(); AliasPayload aliasPayload = ; // AliasPayload | try { 'String' result = apiInstance.alias(aliasPayload); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling HTTPAPIApi#alias"); e.printStackTrace(); } } } ``` -------------------------------- ### Handle.StartWebHandler Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/02-gateway-api.md Starts the HTTP server for the gateway, making it ready to receive incoming events. ```APIDOC ### StartWebHandler ```go func (gw *Handle) StartWebHandler(ctx context.Context) error ``` Starts the HTTP server listening for incoming events. **Parameters**: - `ctx`: Context for server lifecycle **Returns**: Error from server **Port**: Configurable via `Gateway.webPort` config (default 8080) **Blocks**: Until context cancelled or server error occurs ``` -------------------------------- ### PHP Group API Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Shows how to use the group API with the PHP SDK. Basic HTTP authentication must be set up. ```php setUsername('YOUR_USERNAME'); OpenAPITools ::Client ::Configuration::getDefaultConfiguration() ->setPassword('YOUR_PASSWORD'); // Create an instance of the API class $api_instance = new OpenAPITools ::Client ::Api ::HTTPAPIApi(); $groupPayload = ; // GroupPayload | try { $result = $api_instance->group($groupPayload); print_r($result); } catch (Exception $e) { echo 'Exception when calling HTTPAPIApi->group: ', $e->getMessage(), PHP_EOL; } ?> ``` -------------------------------- ### Perl API Client Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Shows how to use the Perl SDK for the HTTP API, covering authentication and calling the 'page' method. This example uses Data::Dumper for output. ```perl use Data::Dumper; use WWW::OPenAPIClient::Configuration; use WWW::OPenAPIClient::HTTPAPIApi; # Configure HTTP basic authorization: writeKeyAuth $WWW::OPenAPIClient::Configuration::username = 'YOUR_USERNAME'; $WWW::OPenAPIClient::Configuration::password = 'YOUR_PASSWORD'; # Create an instance of the API class my $api_instance = WWW::OPenAPIClient::HTTPAPIApi->new(); my $pagePayload = WWW::OPenAPIClient::Object::PagePayload->new(); # PagePayload | eval { my $result = $api_instance->page(pagePayload => $pagePayload); print Dumper($result); }; if ($@) { warn "Exception when calling HTTPAPIApi->page: $@\n"; } ``` -------------------------------- ### Java HTTP API Screen Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Demonstrates how to authenticate using basic auth and call the screen method with a ScreenPayload in Java. ```java import org.openapitools.client.*; import org.openapitools.client.auth.*; import org.openapitools.client.model.*; import org.openapitools.client.api.HTTPAPIApi; import java.io.File; import java.util.*; public class HTTPAPIApiExample { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); // Configure HTTP basic authorization: writeKeyAuth HttpBasicAuth writeKeyAuth = (HttpBasicAuth) defaultClient.getAuthentication("writeKeyAuth"); writeKeyAuth.setUsername("YOUR USERNAME"); writeKeyAuth.setPassword("YOUR PASSWORD"); // Create an instance of the API class HTTPAPIApi apiInstance = new HTTPAPIApi(); ScreenPayload screenPayload = ; // ScreenPayload | try { 'String' result = apiInstance.screen(screenPayload); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling HTTPAPIApi#screen"); e.printStackTrace(); } } } ``` -------------------------------- ### Rust Identify API Call Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html A basic example of how to call the identify API using Rust. This snippet assumes the necessary client and context setup is available. ```rust extern crate HTTPAPIApi; pub fn main() { let identifyPayload = ; // IdentifyPayload let mut context = HTTPAPIApi::Context::default(); let result = client.identify(identifyPayload, &context).wait(); println!("{:?}", result); } ``` -------------------------------- ### Main Function Setup and Runner Initialization Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/09-runner-initialization.md Sets up the main function with context, signal handling, memory watching, and runner initialization. It ensures graceful shutdown and proper exit codes. ```go func main() { c := config.Default log := logger.NewLogger().Child("main") // Setup context with signal handling ctx, shutdownFn := kitctx.NotifyContextWithCallback(func() { log.Infon("Server received termination signal...") }, syscall.SIGINT, syscall.SIGTERM) // Setup memory watcher var wg sync.WaitGroup mem.WatchMemoryLimit(ctx, &wg, mem.WatchWithLogger(log), mem.WatchWithPercentageLoader(c.GetReloadableIntVar(90, 1, "memoryLimitPercentage")), ) // Create and run runner r := runner.New(runner.ReleaseInfo{...}) exitCode := r.Run(ctx, shutdownFn, os.Args) // Cleanup shutdownFn() wg.Wait() os.Exit(exitCode) } ``` -------------------------------- ### Rust Internal API Batch Request Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html A basic example showing how to call the internalBatch method in Rust. This snippet assumes the necessary client and context setup is handled elsewhere. ```rust extern crate InternalAPIApi; pub fn main() { let mut context = InternalAPIApi::Context::default(); let result = client.internalBatch(&context).wait(); println!("{:?}", result); } ``` -------------------------------- ### Execute Application Startup and Lifecycle Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/09-runner-initialization.md Use this function to run the complete application startup and manage its lifecycle. It takes a context, a shutdown function, and command-line arguments, returning an exit code. ```go func (r *Runner) Run(ctx context.Context, shutdownFn func(), args []string) int ``` ```go exitCode := r.Run(ctx, shutdownFn, os.Args) os.Exit(exitCode) ``` -------------------------------- ### Install Dependencies for Config Generator Source: https://github.com/rudderlabs/rudder-server/wiki/RudderStack-Config-Generator Install the necessary dependencies for the RudderStack Config Generator using npm. Ensure Node.js 10.6 or later is installed. ```bash npm install ``` -------------------------------- ### Start Configuration Fetching for Specific Workspaces Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/04-backend-config-api.md Initiates configuration fetching for a specified set of workspaces. Accepts a context and a comma-separated string of workspace IDs. An empty string fetches all workspaces. ```go func (bc *backendConfigImpl) StartWithIDs(ctx context.Context, workspaces string) ``` -------------------------------- ### Get Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/04-backend-config-api.md Retrieves the current configuration for all workspaces. This is useful for getting a snapshot of the system's configuration. ```APIDOC ## Get ### Description Retrieves current configuration for all workspaces. ### Method GET ### Endpoint /config ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **map[string]ConfigT**: Map of workspace ID to configuration #### Response Example { "example": "{\"workspace1\": {\"setting1\": \"value1\"}, \"workspace2\": {\"setting2\": \"value2\"}}" } ERROR HANDLING: - Returns an error if configuration retrieval fails. ``` -------------------------------- ### Java SDK Replay Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Demonstrates how to configure basic authentication and call the replay method using the Java SDK. Ensure you have the necessary client libraries imported. ```java import org.openapitools.client.*; import org.openapitools.client.auth.*; import org.openapitools.client.model.*; import org.openapitools.client.api.InternalAPIApi; import java.io.File; import java.util.*; public class InternalAPIApiExample { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); // Configure HTTP basic authorization: sourceIDAuth HttpBasicAuth sourceIDAuth = (HttpBasicAuth) defaultClient.getAuthentication("sourceIDAuth"); sourceIDAuth.setUsername("YOUR USERNAME"); sourceIDAuth.setPassword("YOUR PASSWORD"); // Create an instance of the API class InternalAPIApi apiInstance = new InternalAPIApi(); try { 'String' result = apiInstance.replay(); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling InternalAPIApi#replay"); e.printStackTrace(); } } } ``` -------------------------------- ### New Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/05-app-lifecycle.md Creates a new application instance with the specified options. This is the entry point for initializing the application. ```APIDOC ## New ### Description Creates a new application instance with the specified options. ### Signature ```go func New(options *Options) App ``` ### Parameters #### Path Parameters * `options` (*Options) - Required - Application options to configure the new instance. ### Returns * `App` - An interface implementation representing the application instance. ``` -------------------------------- ### Identify API Endpoint - Rust Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using Rust. ```rust use reqwest::blocking::Client; use serde_json::json; fn main() -> Result<(), reqwest::Error> { let client = Client::new(); let url = "http://localhost:8080/v1/identify"; let data = json!({ "anonymousId": "a712721c-637a-4211-8712-000000000001", "traits": { "email": "test@example.com", "name": "Test User" } }); let response = client.post(url) .json(&data) .send()?; println!("{}", response.text()?); Ok(()) } ``` -------------------------------- ### PHP SDK Replay Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Illustrates how to configure basic authentication and call the replay method using the PHP SDK. Composer's autoloader is required. ```php setUsername('YOUR_USERNAME'); OpenAPITools Client Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); // Create an instance of the API class $api_instance = new OpenAPITools Client Api InternalAPIApi(); try { $result = $api_instance->replay(); print_r($result); } catch (Exception $e) { echo 'Exception when calling InternalAPIApi->replay: ', $e->getMessage(), PHP_EOL; } ?> ``` -------------------------------- ### Identify API Endpoint - Python Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using Python. ```python import requests import json url = "http://localhost:8080/v1/identify" data = { "anonymousId": "a712721c-637a-4211-8712-000000000001", "traits": { "email": "test@example.com", "name": "Test User" } } headers = { "content-type": "application/json" } response = requests.post(url, data=json.dumps(data), headers=headers) print(response.text) ``` -------------------------------- ### Identify API Endpoint - Perl Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using Perl. ```perl use strict; use warnings; use LWP::UserAgent; use JSON; my $ua = LWP::UserAgent->new; $ua->agent("MyApp/1.0"); my $url = 'http://localhost:8080/v1/identify'; my $data = { anonymousId => 'a712721c-637a-4211-8712-000000000001', traits => { email => 'test@example.com', name => 'Test User' } }; my $json_data = encode_json($data); my $response = $ua->post($url, { 'Content-Type' => 'application/json' }, $json_data); if ($response->is_success) { print $response->decoded_content; } else { die $response->status_line; } ``` -------------------------------- ### Identify API Endpoint - PHP Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using PHP. ```php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://localhost:8080/v1/identify"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_POST, TRUE); $data = json_encode( array( 'anonymousId' => 'a712721c-637a-4211-8712-000000000001', 'traits' => array( 'email' => 'test@example.com', 'name' => 'Test User' ) )); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' )); $response = curl_exec($ch); curl_close($ch); echo $response; ``` -------------------------------- ### Identify API Endpoint - C# Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using C#. ```csharp using (var client = new HttpClient()) { var requestData = new { anonymousId = "a712721c-637a-4211-8712-000000000001", traits = new { email = "test@example.com", name = "Test User" } }; var json = JsonSerializer.Serialize(requestData); var data = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync("http://localhost:8080/v1/identify", data); var responseString = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseString); } ``` -------------------------------- ### C# SDK Replay Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Shows how to set up basic authentication and execute the replay method using the C# SDK. Exceptions are caught for error handling. ```csharp using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; namespace Example { public class replayExample { public void main() { // Configure HTTP basic authorization: sourceIDAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; // Create an instance of the API class var apiInstance = new InternalAPIApi(); try { // Replay 'String' result = apiInstance.replay(); Debug.WriteLine(result); } catch (Exception e) { Debug.Print("Exception when calling InternalAPIApi.replay: " + e.Message ); } } } } ``` -------------------------------- ### Create New App Instance Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/05-app-lifecycle.md Use `New` to create a new application instance with specified options. Ensure `ENTERPRISE_TOKEN` is set in the environment if needed. ```go func New(options *Options) App ``` ```go app := app.New(&app.Options{ EnterpriseToken: os.Getenv("ENTERPRISE_TOKEN"), NormalMode: true, }) ``` -------------------------------- ### Identify API Endpoint - JavaScript Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using JavaScript. ```javascript fetch('http://localhost:8080/v1/identify', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ "anonymousId": "a712721c-637a-4211-8712-000000000001", "traits": { "email": "test@example.com", "name": "Test User" } }) }).then(response => response.json()) .then(data => console.log(data)); ``` -------------------------------- ### Retrieve App Options Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/05-app-lifecycle.md The `Options` method returns the application's initialization options. ```go func (a *app) Options() *Options ``` -------------------------------- ### Identify API Endpoint - Obj-C Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using Objective-C. ```objectivec NSURL *url = [NSURL URLWithString:@"http://localhost:8080/v1/identify"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/json" forHTTPHeaderField:@"content-type"]; NSDictionary *traits = @{ @"email": @"test@example.com", @"name": @"Test User" }; NSDictionary *bodyDict = @{ @"anonymousId": @"a712721c-637a-4211-8712-000000000001", @"traits": traits }; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bodyDict options:0 error:nil]; [request setHTTPBody:jsonData]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"Error: %@\n%@", error, response); } else { NSString *strData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@\n%@", strData, response); } }]; [dataTask resume]; ``` -------------------------------- ### Identify API Endpoint - Dart Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using Dart. ```dart var client = http.Client(); client.post(Uri.parse('http://localhost:8080/v1/identify'), headers: { 'content-type': 'application/json' }, body: json.encode({ 'anonymousId': 'a712721c-637a-4211-8712-000000000001', 'traits': { 'email': 'test@example.com', 'name': 'Test User' } })).then((response) { print(response.body); }); ``` -------------------------------- ### PHP SDK Extract Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Shows how to set up basic authentication and make an extract call using the PHP SDK. Includes try-catch block for error management. ```php setUsername('YOUR_USERNAME'); OpenAPITools Client Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); // Create an instance of the API class $api_instance = new OpenAPITools Client Api InternalAPIApi(); try { $result = $api_instance->extract(); print_r($result); } catch (Exception $e) { echo 'Exception when calling InternalAPIApi->extract: ', $e->getMessage(), PHP_EOL; } ?> ``` -------------------------------- ### Identify API Endpoint - Java Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using Java. ```java OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "{\n \"anonymousId\": \"a712721c-637a-4211-8712-000000000001\",\n \"traits\": {\n \"email\": \"test@example.com\",\n \"name\": \"Test User\"\n }\n}"); Request request = new Request.Builder() .url("http://localhost:8080/v1/identify") .post(body) .addHeader("content-type", "application/json") .build(); Response response = client.newCall(request).execute(); ``` -------------------------------- ### Identify API Endpoint - Curl Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using Curl. ```curl curl --request POST \ --url http://localhost:8080/v1/identify \ --header 'content-type: application/json' \ --data '{ "anonymousId": "a712721c-637a-4211-8712-000000000001", "traits": { "email": "test@example.com", "name": "Test User" } }' ``` -------------------------------- ### Objective-C SDK Replay Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Illustrates how to set up basic authentication and invoke the replay method with the Objective-C SDK. Completion handlers are used for asynchronous operations. ```objectivec Configuration *apiConfig = [Configuration sharedConfig]; // Configure HTTP basic authorization (authentication scheme: sourceIDAuth) [apiConfig setUsername:@"YOUR_USERNAME"]; [apiConfig setPassword:@"YOUR_PASSWORD"]; // Create an instance of the API class InternalAPIApi *apiInstance = [[InternalAPIApi alloc] init]; // Replay [apiInstance replayWithCompletionHandler: ^('String' output, NSError* error) { if (output) { NSLog(@"%@", output); } if (error) { NSLog(@"Error: %@", error); } }]; ``` -------------------------------- ### Identify API Endpoint - Android Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to call the identify API endpoint using Android (Java/Kotlin). ```java OkHttpClient client = new OkHttpClient(); MediaType JSON = MediaType.get("application/json; charset=utf-8"); JSONObject jsonObject = new JSONObject(); jsonObject.put("anonymousId", "a712721c-637a-4211-8712-000000000001"); JSONObject traits = new JSONObject(); traits.put("email", "test@example.com"); traits.put("name", "Test User"); jsonObject.put("traits", traits); RequestBody body = RequestBody.create(JSON, jsonObject.toString()); Request request = new Request.Builder() .url("http://localhost:8080/v1/identify") .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { e.printStackTrace(); } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); // Handle response Log.d("RudderSDK", responseBody.string()); } } }); ``` -------------------------------- ### Application Initialization Options Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/08-types-reference.md Defines the configuration options for initializing the application, controlling operational modes, database behavior, profiling, and enterprise features. ```go type Options struct { NormalMode bool // Normal operation mode DegradedMode bool // Degraded mode ClearDB bool // Clear database on startup Cpuprofile string // CPU profile output path Memprofile string // Memory profile output path VersionFlag bool // Print version and exit EnterpriseToken string // Enterprise license token } ``` -------------------------------- ### Python Group API Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Provides a Python example for the group API. Basic HTTP authentication is required. ```python from __future__ import print_statement import time import openapi_client from openapi_client.rest import ApiException from pprint import pprint # Configure HTTP basic authorization: writeKeyAuth openapi_client.configuration.username = 'YOUR_USERNAME' openapi_client.configuration.password = 'YOUR_PASSWORD' # Create an instance of the API class api_instance = openapi_client.HTTPAPIApi() groupPayload = # GroupPayload | try: # Group api_response = api_instance.group(groupPayload) pprint(api_response) except ApiException as e: print("Exception when calling HTTPAPIApi->group: %s\n" % e) ``` -------------------------------- ### Initialize and Configure Rudder Server Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html This snippet shows the initial setup and configuration of the Rudder Server. It involves setting up event handlers and configuring the server's behavior based on incoming data. ```javascript function example() { return true; } ``` -------------------------------- ### Start RudderStack Config Generator Source: https://github.com/rudderlabs/rudder-server/wiki/RudderStack-Config-Generator Start the RudderStack Config Generator application. It typically runs on port 3000. ```bash npm start ``` -------------------------------- ### PHP SDK Sample for Screen API Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Demonstrates how to use the PHP SDK to call the screen API. Ensure you have configured HTTP basic authorization with your write key. ```php setUsername('YOUR_USERNAME'); OpenAPITools\Client\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); // Create an instance of the API class $api_instance = new OpenAPITools\Client\Api\HTTPAPIApi(); $screenPayload = ; // ScreenPayload | try { $result = $api_instance->screen($screenPayload); print_r($result); } catch (Exception $e) { echo 'Exception when calling HTTPAPIApi->screen: ', $e->getMessage(), PHP_EOL; } ?> ``` -------------------------------- ### Rust Alias Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html This Rust example shows how to send an alias event. It uses a default context for API calls. ```rust extern crate HTTPAPIApi; pub fn main() { let aliasPayload = ; // AliasPayload let mut context = HTTPAPIApi::Context::default(); let result = client.alias(aliasPayload, &context).wait(); println!("{:?}", result); } ``` -------------------------------- ### Handle Rudder Initialization Options Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Demonstrates how to initialize the Rudder client with various options, such as setting a cookie domain or enabling debug mode. ```javascript var rudder = rudderclient.init("http://localhost:8080", "http://localhost:8080", { "cookieDomain": "example.com" }); ``` ```javascript var rudder = rudderclient.init("http://localhost:8080", "http://localhost:8080", { "logLevel": "debug" }); ``` -------------------------------- ### JavaScript (Node.js) SDK Replay Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Demonstrates how to configure basic authentication and call the replay method using the JavaScript SDK for Node.js. A callback function handles the response or errors. ```javascript var RudderStackHttpApi = require('rudder_stack_http_api'); var defaultClient = RudderStackHttpApi.ApiClient.instance; // Configure HTTP basic authorization: sourceIDAuth var sourceIDAuth = defaultClient.authentications['sourceIDAuth']; sourceIDAuth.username = 'YOUR USERNAME'; sourceIDAuth.password = 'YOUR PASSWORD'; // Create an instance of the API class var api = new RudderStackHttpApi.InternalAPIApi() var callback = function(error, data, response) { if (error) { console.error(error); } else { console.log('API called successfully. Returned data: ' + data); } }; api.replay(callback); ``` -------------------------------- ### JavaScript HTTP API Screen Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Provides a JavaScript example for using the screen method with a ScreenPayload and a callback for handling responses. ```javascript var RudderStackHttpApi = require('rudder_stack_http_api'); var defaultClient = RudderStackHttpApi.ApiClient.instance; // Configure HTTP basic authorization: writeKeyAuth var writeKeyAuth = defaultClient.authentications['writeKeyAuth']; writeKeyAuth.username = 'YOUR USERNAME'; writeKeyAuth.password = 'YOUR PASSWORD'; // Create an instance of the API class var api = new RudderStackHttpApi.HTTPAPIApi() var screenPayload = ; // {ScreenPayload} var callback = function(error, data, response) { if (error) { console.error(error); } else { console.log('API called successfully. Returned data: ' + data); } }; api.screen(screenPayload, callback); ``` -------------------------------- ### Curl Alias Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to make an alias call using Curl. Ensure to replace [[basicHash]] with your actual authorization hash. ```curl curl -X POST \ -H "Authorization: Basic [[basicHash]]" \ -H "Accept: text/plain; charset=utf-8" \ -H "Content-Type: application/json" \ "/v1/v1/alias" \ -d '{ \ "previousId" : "previousId", \ "context" : { \ "traits" : { \ "trait1" : "trait1" \ }, \ "library" : { \ "name" : "name" \ }, \ "ip" : "ip" \ }, \ "userId" : "userId", \ "timestamp" : "2000-01-23T04:56:07.000+00:00" \ }' ``` -------------------------------- ### Gateway StartWebHandler Method Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/02-gateway-api.md Starts the HTTP server for the gateway, making it ready to accept incoming events. The server listens on a configurable port and blocks until the context is cancelled or an error occurs. ```go func (gw *Handle) StartWebHandler(ctx context.Context) error ``` -------------------------------- ### Perl Batch API Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of using the Perl SDK to interact with the batch endpoint. Authentication is set using username and password. ```perl use Data::Dumper; use WWW::OPenAPIClient::Configuration; use WWW::OPenAPIClient::HTTPAPIApi; # Configure HTTP basic authorization: writeKeyAuth $WWW::OPenAPIClient::Configuration::username = 'YOUR_USERNAME'; $WWW::OPenAPIClient::Configuration::password = 'YOUR_PASSWORD'; # Create an instance of the API class my $api_instance = WWW::OPenAPIClient::HTTPAPIApi->new(); my $batchPayload = WWW::OPenAPIClient::Object::BatchPayload->new(); # BatchPayload | eval { my $result = $api_instance->batch(batchPayload => $batchPayload); print Dumper($result); }; if ($@) { warn "Exception when calling HTTPAPIApi->batch: $@\n"; } ``` -------------------------------- ### C# Alias Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html This C# example shows how to send an alias event. Basic HTTP authentication is configured using your username and password. ```csharp using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; namespace Example { public class aliasExample { public void main() { // Configure HTTP basic authorization: writeKeyAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; // Create an instance of the API class var apiInstance = new HTTPAPIApi(); var aliasPayload = new AliasPayload(); // AliasPayload | try { // Alias 'String' result = apiInstance.alias(aliasPayload); Debug.WriteLine(result); } catch (Exception e) { Debug.Print("Exception when calling HTTPAPIApi.alias: " + e.Message ); } } } } ``` -------------------------------- ### Create Group using Java SDK Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html This Java example demonstrates how to create a group using the Rudder Server SDK. Configure HTTP basic authentication with your username and password. ```java import org.openapitools.client.*; import org.openapitools.client.auth.*; import org.openapitools.client.model.*; import org.openapitools.client.api.HTTPAPIApi; import java.io.File; import java.util.*; public class HTTPAPIApiExample { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); // Configure HTTP basic authorization: writeKeyAuth HttpBasicAuth writeKeyAuth = (HttpBasicAuth) defaultClient.getAuthentication("writeKeyAuth"); writeKeyAuth.setUsername("YOUR USERNAME"); writeKeyAuth.setPassword("YOUR PASSWORD"); // Create an instance of the API class HTTPAPIApi apiInstance = new HTTPAPIApi(); GroupPayload groupPayload = ; // GroupPayload | try { String result = apiInstance.group(groupPayload); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling HTTPAPIApi#group"); e.printStackTrace(); } } } ``` -------------------------------- ### PHP Batch API Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Shows how to call the batch endpoint using the PHP SDK. Basic HTTP authentication is configured via username and password. ```php setUsername('YOUR_USERNAME'); OpenAPITools ::Client ::Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); // Create an instance of the API class $api_instance = new OpenAPITools ::Client ::Api ::HTTPAPIApi(); $batchPayload = ; // BatchPayload | try { $result = $api_instance->batch($batchPayload); print_r($result); } catch (Exception $e) { echo 'Exception when calling HTTPAPIApi->batch: ', $e->getMessage(), PHP_EOL; } ?> ``` -------------------------------- ### Dart Alias Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to make an alias call using the Dart SDK. Initializes the default API client and handles potential exceptions. ```dart import 'package:openapi/api.dart'; final api_instance = DefaultApi(); final AliasPayload aliasPayload = new AliasPayload(); // AliasPayload | try { final result = await api_instance.alias(aliasPayload); print(result); } catch (e) { print('Exception when calling DefaultApi->alias: $e\n'); } ``` -------------------------------- ### Options Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/05-app-lifecycle.md Retrieves the application's initialization options. This can be useful for inspecting or logging the configuration used by the application. ```APIDOC ## Options ### Description Returns the application's initialization options that were used when the application instance was created. ### Signature ```go func (a *app) Options() *Options ``` ### Parameters This method does not take any parameters. ### Returns * `*Options` - A pointer to the Options struct containing the application's configuration. ``` -------------------------------- ### ReleaseInfo Struct Source: https://github.com/rudderlabs/rudder-server/blob/master/_autodocs/09-runner-initialization.md Defines build and version information passed from main.go to the runner. ```go type ReleaseInfo struct { Version string // Semantic version (e.g., "v1.0.0") Commit string // Git commit hash BuildDate string // Build timestamp BuiltBy string // Builder identifier EnterpriseToken string // Enterprise license } ``` -------------------------------- ### Dart HTTP API Track Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Shows how to use the Dart SDK to call the track API. This example assumes the DefaultApi is configured and ready to use. ```dart import 'package:openapi/api.dart'; final api_instance = DefaultApi(); final TrackPayload trackPayload = new TrackPayload(); // TrackPayload | try { final result = await api_instance.track(trackPayload); print(result); } catch (e) { print('Exception when calling DefaultApi->track: $e\n'); } ``` -------------------------------- ### Objective-C Alias Example Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Example of how to make an alias call using Objective-C. Configures HTTP basic authorization and uses a completion handler for the API response. ```objc Configuration *apiConfig = [Configuration sharedConfig]; // Configure HTTP basic authorization (authentication scheme: writeKeyAuth) [apiConfig setUsername:@"YOUR_USERNAME"]; [apiConfig setPassword:@"YOUR_PASSWORD"]; // Create an instance of the API class HTTPAPIApi *apiInstance = [[HTTPAPIApi alloc] init]; AliasPayload *aliasPayload = ; // // Alias [apiInstance aliasWith:aliasPayload completionHandler: ^('String' output, NSError* error) { if (output) { NSLog(@"%@", output); } if (error) { NSLog(@"Error: %@", error); } }]; ``` -------------------------------- ### HTML Preformatted Text Styling (GET) Source: https://github.com/rudderlabs/rudder-server/blob/master/gateway/openapi/index.html Specific styling for HTML preformatted blocks labeled as 'get' requests. Uses a green background for the data-type label. ```css pre.language-html[data-type="get"]:before { background-color: green; } ```