Getting Started
Install the SDK
Once your Web Console is setup and you have created some experiments, you can install our SDKs through your package manager, a CDN or by directly importing it.
- Javascript
- Python3
- React
- Swift
- Vue2
- Vue3
- Java
- Go
- .NET
- PHP
- Ruby
- Flutter/Dart
NPM
npm install --save @absmartly/javascript-sdk
Direct Import
<script src="https://unpkg.com/@absmartly/javascript-sdk/dist/absmartly.min.js"></script>
ABsmartly’s Javascript SDK depends on support for a native ES6 promise implementation. If your environment does not support ES6 promises, you can polyfill.
The ABsmartly Python SDK is compatible with Python 3. It provides both a blocking and an asynchronous interfaces.
Pip
pip install absmartly==0.1.4
Dependencies
setuptools~=60.2.0
requests~=2.28.1
urllib3~=1.26.12
jsons~=1.6.3
npm install --save @absmartly/react-sdk
The ABSmartly React SDK selects and renders treatments on the client-side. If you wish to use server-side rendering with NextJS or similar, you will need to use the Javascript SDK or a combination of the two.
Swift Package Manager
- In Xcode go to:
File -> Swift Packages -> Add Package Dependency...
- Enter the ABsmartly Swift SDK GitHub repository: https://github.com/absmartly/swift-sdk
- Select the SDK version (latest recommended)
- Select the ABSmartly library
Cocoapods
To install the ABsmartly SDK with CocoaPods, add the following lines to
your Podfile
:
pod 'ABSmartlySwiftSDK', '~> 1.0.2'
Run the following command to update your Xcode project:
pod install
Using NPM
npm install --save @absmartly/vue2-sdk
Directly Import With unpkg.com (Optimized and Pre-Built)
Simply add the following code to your head
section to include the latest
published version.
<script src="https://unpkg.com/@absmartly/vue2-sdk"></script>
Using NPM
npm install --save @absmartly/vue3-sdk
Directly Import With unpkg.com (Optimized and Pre-Built)
Simply add the following code to your head
section to include the latest
published version.
<script src="https://unpkg.com/@absmartly/vue3-sdk"></script>
The ABsmartly Java SDK is compatible with Java versions 1.6 and later. It
provides both a blocking and an asynchronous interface. The asynchronous
functions return a custom backport
of the Java 8 CompletableFuture
API.
Android
The ABsmartly SDK is compatible with Android 4.4 and later (API level 19+).
The android.permission.INTERNET
permission is required. To add this permission
to your application ensure the following line is present in the
AndroidManifest.xml
file:
<uses-permission android:name="android.permission.INTERNET"/>
If you target Android 6.0 or earlier, a few extra steps are outlined below for installation and initialization.
Gradle
To install the ABSmartly SDK, place the following in your build.gradle
and
replace {VERSION} with the latest SDK version available in MavenCentral.
dependencies {
compile 'com.absmartly.sdk:core-api:{VERSION}'
}
Maven
To install the ABSmartly SDK, place the following in your pom.xml
and
replace {VERSION} with the latest SDK version available in MavenCentral.
<dependency>
<groupId>com.absmartly.sdk</groupId>
<artifactId>core-api</artifactId>
<version>{VERSION}</version>
</dependency>
When targeting Android 6.0 or earlier, the default Java Security Provider will not work. Using Conscrypt is recommended. Follow these instructions to install it as dependency.
The ABsmartly Go SDK is compatible with Go versions 1.15 and later. It provides both a blocking and an asynchronous interfaces.
Go Modules
require github.com/absmartly/go-sdk
Dependencies
sh ./run.sh
The .NET SDK targets .NET Standard 2.0 and .NET 5, but is also fully compatible with .NET 6.
Nuget
dotnet add package ABSmartly.Sdk --version 1.0.0
The ABsmartly PHP SDK is compatible with PHP versions 7.4 and later. For the best performance and code readability, PHP 8.1 or later is recommended. This SDK is being constantly tested with the nightly builds of PHP, to ensure it is compatible with the latest PHP version.
ABsmartly PHP SDK can be installed with composer:
composer require absmartly/php-sdk
The ABsmartly Ruby SDK is compatible with Ruby versions 2.7 and later. For the best performance and code readability, Ruby 3 or later is recommended. This SDK is being constantly tested with the nightly builds of Ruby, to ensure it is compatible with the latest Ruby version.
With Bundler
bundle add absmartly
Without Bundler
gem install absmartly
The ABsmartly Flutter SDK is compatible with Dart versions 2.18.6 and later.
To install the ABSmartly SDK, place the following in your pubspec.yaml
and replace version with the latest SDK version available in pub.dev.
absmartly_sdk: ^version
Import and Initialize the SDK
Once the SDK is installed, it can be initialized in your project.
The following examples assume that an Api Key with SDK permissions, an Application, and an Environment have been created in the ABsmartly Web Console.
- Javascript
- Python3
- React
- Swift
- Vue2
- Vue3
- Java
- Go
- .NET
- PHP
- Ruby
- Flutter/Dart
// ES6 Modules
import absmartly from "@absmartly/javascript-sdk";
// For commonJS, use:
// const absmartly = require("@absmartly/javascript-sdk");
const sdk = new absmartly.SDK({
endpoint: "https://your-company.absmartly.io/v1",
apiKey: process.env.ABSMARTLY_API_KEY,
environment: process.env.NODE_ENV,
application: process.env.APPLICATION_NAME,
});
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries | number | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
timeout | number | ❌ | 3000 | An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger | (context, eventName, data) => void | ❌ | See Using a Custom Event Logger below | A callback function which runs after SDK events. |
def main():
client_config = ClientConfig()
client_config.endpoint = "https://your-company.absmartly.io/v1"
client_config.api_key = "test"
client_config.application = "www"
client_config.environment = "prod"
default_client_config = DefaultHTTPClientConfig()
default_client = DefaultHTTPClient(default_client_config)
sdk_config = ABSmartlyConfig()
sdk_config.client = Client(client_config, default_client)
sdk = ABSmartly(sdk_config)
context_config = ContextConfig()
ctx = sdk.create_context(context_config)
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
max_retries | number | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
connection_timeout | number | ❌ | 3 | An amount of time, in seconds, before the SDK will stop trying to connect. |
context_event_logger | (self, event_type: EventType, data: object) | ❌ | See Using a Custom Event Logger below | A callback function which runs after SDK events. |
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import ABSmartly from "@absmartly/react-sdk";
const contextOptions = {
units: {
userId: "123",
session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8",
email: "[email protected]",
deviceId: "345",
},
};
ReactDOM.render(
<ABSmartly
sdkOptions={{
endpoint: "https://your-company.absmartly.io/v1",
apiKey: process.env.ABSMARTLY_API_KEY,
application: process.env.APPLICATION_NAME,
environment: process.env.NODE_ENV,
}}
contextOptions={contextOptions}
>
<App />
</ABSmartly>,
document.getElementById("root")
);
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries | number | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
timeout | number | ❌ | 3000 | An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger | (context, eventName, data) => void | ❌ | See Using a Custom Event Logger below | A callback function which runs after SDK events. |
Initializing the SDK with a Pre-Fetched Context
If you have used the Javascript SDK to create a context, you can pass it directly into the Provider component, like so:
ReactDOM.render(
<ABSmartly context={context}>
<App />
</ABSmartly>,
document.getElementById("root")
);
If you are using NextJS and want to fetch the context on the server side,
you can leverage getServerSideProps
and add the ABsmartly Provider on a
per-page basis. For example:
export const getServerSideProps: GetServerSideProps = async () => {
const sdkOptions = {
endpoint: "https://<your-assigned-subdomain>.absmartly.io/v1",
apiKey: "<your-api-key>",
application: "web",
environment: process.env.NODE_ENV
}
const serverSDK = new absmartly.SDK(sdkOptions)
const contextOptions = {
units: {
user_id: "123",
anonymous_id: "456",
device_id: "789",
}
}
const context = serverSDK.createContext(contextOptions);
await context.ready();
return {
props: {
contextData: context.data(), contextOptions, sdkOptions
},
};
}
export default function Home({ contextData, contextOptions, sdkOptions }) {
const clientSDK = new absmartly.SDK(sdkOptions)
const clientContext = clientSDK.createContextWith(contextOptions, contextData);
return (
<ABsmartly context={clientContext}>
{/* Your page content */}
</ABsmartly>
)
}
import ABSmartly
let sdk: ABSmartlySDK
do {
let clientConfig = ClientConfig(
apiKey: ProcessInfo.processInfo.environment["ABSMARTLY_API_KEY"] ?? "",
application: ProcessInfo.processInfo.environment["ABSMARTLY_APPLICATION"] ?? "",
endpoint: "https://your-company.absmartly.io/v1",
environment: ProcessInfo.processInfo.environment["ABSMARTLY_ENVIRONMENT"] ?? ""))
let client = try DefaultClient(config: clientConfig)
let sdkConfig = ABSmartlyConfig(client: client)
sdk = try ABSmartlySDK(config: sdkConfig)
} catch {
print(error.localizedDescription)
return
}
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries | number | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
timeout | number | ❌ | 3000 | An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger | (context, eventName, data) => void | ❌ | See Using a Custom Event Logger below | A callback function which runs after SDK events. |
import absmartly from "@absmartly/vue2-sdk";
// For commonJS, use:
// const absmartly = require('@absmartly/vue2-sdk');
// Somewhere in your application initialization code, before mounting your Vue application
Vue.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://your-company.absmartly.io/v1",
apiKey: ABSMARTLY_API_KEY,
environment: "production",
application: "website",
},
context: {
units: {
session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8",
},
},
attributes: {
user_agent: navigator.userAgent,
},
});
This makes the $absmartly
extension available in every Vue instance.
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries | number | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
timeout | number | ❌ | 3000 | An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger | (context, eventName, data) => void | ❌ | See Using a Custom Event Logger below | A callback function which runs after SDK events. |
const absmartly = require('@absmartly/vue3-sdk');
// OR with ES6 modules:
import absmartly from '@absmartly/vue3-sdk';
// create vue app ...
app.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: 'https://your-company.absmartly.io/v1',
apiKey: ABSMARTLY_API_KEY,
environment: "production",
application: "website",
},
context: {
units: {
session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
},
},
attributes: {
user_agent: navigator.userAgent
},
overrides: {
exp_test_development: 1
}
});
This makes the $absmartly
extension available in every Vue instance.
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries | number | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
timeout | number | ❌ | 3000 | An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger | (context, eventName, data) => void | ❌ | See Using a Custom Event Logger below | A callback function which runs after SDK events. |
import com.absmartly.sdk.*;
public class Example {
static public void main(String[] args) {
final ClientConfig clientConfig = ClientConfig.create()
.setEndpoint("https://your-company.absmartly.io/v1")
.setAPIKey("YOUR-API-KEY")
.setApplication("website") // created in the ABSmartly Web Console
.setEnvironment("development"); // created in the ABSmartly Web Console
final Client absmartlyClient = Client.create(clientConfig);
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(absmartlyClient);
final ABSmartly sdk = ABSmartly.create(sdkConfig);
// ...
}
}
When targeting Android 6.0 or earlier, set the default Java Security Provider for SSL to Conscrypt by creating the Client instance as follows:
import com.absmartly.sdk.*;
import org.conscrypt.Conscrypt;
// ...
final ClientConfig clientConfig = ClientConfig.create()
.setEndpoint("https://your-company.absmartly.io/v1")
.setAPIKey("YOUR-API-KEY")
.setApplication("website") // created in the ABSmartly Web Console
.setEnvironment("development"); // created in the ABSmartly Web Console
final DefaultHTTPClientConfig httpClientConfig = DefaultHTTPClientConfig.create()
.setSecurityProvider(Conscrypt.newProvider());
final DefaultHTTPClient httpClient = DefaultHTTPClient.create(httpClientConfig);
final Client absmartlyClient = Client.create(clientConfig, httpClient);
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(absmartlyClient);
final ABSmartly sdk = ABSmartly.create(sdkConfig);
// ...
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries | number | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
timeout | number | ❌ | 3000 | An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger | (context, eventName, data) => void | ❌ | See Using a Custom Event Logger below | A callback function which runs after SDK events. |
func main() {
var clientConfig = ClientConfig{
Endpoint_: "https://your-company.absmartly.io/v1",
ApiKey_: os.Getenv("ABSMARTLY_APIKEY"),
Application_: os.Getenv(`ABSMARTLY_APPLICATION`), // created in the ABSmartly web console
Environment_: os.Getenv(`ABSMARTLY_ENVIRONMENT`) // created in the ABSmartly web console
}
var sdkConfig = ABSmartlyConfig{Client_: CreateDefaultClient(clientConfig)}
var sdk = Create(sdkConfig)
// ...
}
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries | number | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
timeout | number | ❌ | 3000 | An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger | (context, eventName, data) => void | ❌ | See Using a Custom Event Logger below | A callback function which runs after SDK events. |
If your project uses .NET dependency injection, the default setup for the SDK can be used:
using ABSmartly;
using ABSmartly.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddABSmartly(builder.Configuration.GetSection("ABSmartly"), HttpClientConfig.CreateDefault());
...
{
"ABSmartly": {
"Environment": "development",
"Application": "website",
"Endpoint": "https://your-company.absmartly.io/v1",
"ApiKey": "YOUR-API-KEY"
}
}
The ABSdk
instance is then added as a singleton and can be injected wherever
necessary:
using ABSmartly;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class Test : ControllerBase
{
private readonly ABSdk \_abSdk;
public Test(ABSdk abSdk)
{
_abSdk = abSdk;
}
}
The AddABSmartly
extension method allows for configuring SDK settings, configuring HTTP
connection settings, injecting custom implementations of context-specific services
and configuring additional HTTP requests policies using Polly.
Alternatively, an SDK instance can be created manually like in the following example:
using ABSmartly;
using ABSmartly.Services;
using Microsoft.Extensions.DependencyInjection;
var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
var abSdk = new ABSdk(new ABSdkHttpClientFactory(httpClientFactory), new ABSmartlyServiceConfiguration
{
Environment = "development",
Application = "website",
Endpoint = "https://your-company.absmartly.io/v1",
ApiKey = "YOUR-API-KEY"
});
...
The SDK uses IHttpClientFactory
abstraction to effectively manage the HTTP
connections pool. This factory is injected using IABSdkHttpClientFactory
as seen in the example above. If you require custom behavior or implementation,
you can inject your own implementation of the IHttpClientFactory
or
the IABSdkHttpClientFactory
.
If you are injecting your own IABSdkHttpClientFactory
implementation, make
sure it creates named IHttpClient
instances with the name ABSmartlySDK.HttpClient
(you can use a static field in the ABSdk
class, ABSdk.HttpClientName
).
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries | number | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
timeout | number | ❌ | 3000 | An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger | (context, eventName, data) => void | ❌ | See Using a Custom Event Logger below | A callback function which runs after SDK events. |
use \ABSmartly\SDK\SDK;
$sdk = SDK::createWithDefaults(
endpoint: 'https://your-company.absmartly.io/v1',
apiKey: $apiKey,
environment: $environment,
application: $application
);
Note that the above example uses named parameters introduced in PHP 8.0. Although it is strongly recommended to use the latest PHP version, PHP 7.4 is supported as well. On PHP 7.4, parameters are only passed in their order, as named parameters are not supported.
For example:
use \ABSmartly\SDK\SDK;
$sdk = SDK::createWithDefaults(
'https://your-company.absmartly.io/v1', $apiKey, $environment, $application,
);
The above is a short-cut that creates an SDK instance quickly using default values. If you would like granular choice of individual components (such as a custom event logger), it can be done as following:
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Client\Client;
use ABSmartly\SDK\Config;
use ABSmartly\SDK\SDK;
use ABSmartly\SDK\Context\ContextConfig;
use ABSmartly\SDK\Context\ContextEventLoggerCallback;
$clientConfig = new ClientConfig('', '', '', '');
$client = new Client($clientConfig);
$config = new Config($client);
$sdk = new SDK($config);
$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(new ContextEventLoggerCallback(
function (string $event, ?object $data) {
// Custom callback
}
));
$context = $sdk->createContext($contextConfig);
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries | int | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
timeout | int | ❌ | 3000 | An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger | \ABSmartly\SDK\Context\ContextEventLogger | ❌ | null , See Using a Custom Event Logger below | A callback function which runs after SDK events. |
Absmartly.configure_client do |config|
config.endpoint = "https://your-company.absmartly.io/v1"
config.api_key = "YOUR-API-KEY"
config.application = "website"
config.environment = "development"
end
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries | number | ❌ | 5 | The number of retries before the SDK stops trying to connect. |
timeout | number | ❌ | 3000 | An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger | (context, eventName, data) => void | ❌ | See "Using a Custom Event Logger" below | A callback function which runs after SDK events. |
void main() async{
final ClientConfig clientConfig = ClientConfig()
..setEndpoint("https://your-company.absmartly.io/v1")
..setAPIKey("YOUR API KEY")
..setApplication("website")
..setEnvironment("development");
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(Client.create(clientConfig));
final ABSmartly sdk = ABSmartly(sdkConfig);
}
SDK Options
Config | Type | Required? | Default | Description |
---|---|---|---|---|
endpoint | string | ✅ | undefined | The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey | string | ✅ | undefined | Your API key which can be found on the Web Console. |
environment | "production" or "development" | ✅ | undefined | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application | string | ✅ | undefined | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
Using a Custom Event Logger
- Javascript
- Python3
- React
- Swift
- Vue2
- Vue3
- Java
- Go
- .NET
- PHP
- Flutter/Dart
The ABsmartly SDK can be instantiated with an event logger used for all
contexts. In addition, an event logger can be specified when creating a
particular context, in the createContext
call options. The example below
illustrates this with the implementation of the default event logger, used if
none is specified.
const sdk = new absmartly.SDK({
endpoint: "https://sandbox-api.absmartly.com/v1",
apiKey: process.env.ABSMARTLY_API_KEY,
environment: process.env.NODE_ENV,
application: process.env.APPLICATION_NAME,
eventLogger: (context, eventName, data) => {
if (eventName == "error") {
console.error(data);
}
},
});
The data parameter depends on the type of event. Currently, the SDK logs the following events:
eventName | when | data |
---|---|---|
"error" | Context receives an error | error object thrown |
"ready" | Context turns ready | data used to initialize the context |
"refresh" | Context.refresh() method succeeds | data used to refresh the context |
"publish" | Context.publish() method succeeds | data sent to the ABsmartly event collector |
"exposure" | Context.treatment() method succeeds on first exposure | exposure data enqueued for publishing |
"goal" | Context.track() method succeeds | goal data enqueued for publishing |
"finalize" | Context.finalize() method succeeds the first time | undefined |
The ABsmartly SDK can be instantiated with an event logger used for all
contexts. In addition, an event logger can be specified when creating a
particular context, in the ContextConfig
.
class EventType(Enum):
ERROR = "error"
READY = "ready"
REFRESH = "refresh"
PUBLISH = "publish"
EXPOSURE = "exposure"
GOAL = "goal"
CLOSE = "close"
class ContextEventLogger:
@abstractmethod
def handle_event(self, event_type: EventType, data: object):
raise NotImplementedError
The data parameter depends on the type of event. Currently, the SDK logs the following events:
event | when | data |
---|---|---|
Error | Context receives an error | Throwable object |
Ready | Context turns ready | ContextData used to initialize the context |
Refresh | Context.refresh() method succeeds | ContextData used to refresh the context |
Publish | Context.publish() method succeeds | PublishEvent sent to the ABsmartly event collector |
Exposure | Context.getTreatment() method succeeds on first exposure | Exposure enqueued for publishing |
Goal | Context.track() method succeeds | GoalAchievement enqueued for publishing |
Close | Context.close() method succeeds the first time | null |
The ABsmartly SDK can be instantiated with an event logger used for all
contexts. In addition, an event logger can be specified when creating a
particular context, in the createContext
call options. The example below
illustrates this with the implementation of the default event logger, used if
none is specified.
ReactDOM.render(
<ABSmartly
sdkOptions={{
endpoint: "https://sandbox.absmartly.io/v1",
apiKey: process.env.ABSMARTLY_API_KEY,
application: process.env.APPLICATION_NAME,
environment: process.env.NODE_ENV,
eventLogger: (context, eventName, data) => {
if (eventName == "error") {
console.error(data);
}
},
}}
contextOptions={contextOptions}
>
<App />
</ABSmartly>,
document.getElementById("root")
);
The data parameter depends on the type of event. Currently, the SDK logs the following events:
eventName | when | data |
---|---|---|
"error" | Context receives an error | error object thrown |
"ready" | Context turns ready | data used to initialize the context |
"refresh" | Context.refresh() method succeeds | data used to refresh the context |
"publish" | Context.publish() method succeeds | data sent to the ABsmartly event collector |
"exposure" | Context.treatment() method succeeds on first exposure | exposure data enqueued for publishing |
"goal" | Context.track() method succeeds | goal data enqueued for publishing |
"finalize" | Context.finalize() method succeeds the first time | undefined |
The ABsmartly SDK can be instantiated with an event logger used for all
contexts. In addition, an event logger can be specified when creating a
particular context, in the ContextConfig
.
// Example implementation
public class CustomEventLogger : ContextEventLogger {
public func handleEvent(context: Context, event: ContextEventLoggerEvent) {
switch event {
case let .exposure(exposure):
print("exposed to experiment: \(exposure.name)")
case let .goal(goal):
print("goal tracked: \(goal.name)")
case let .error(error):
print("error: ", error.localizedDescription)
case let .publish(event):
break
case let .ready(data):
break
case let .refresh(data):
break
case .close:
break
}
}
}
// for all contexts, during sdk initialization
let absmartlyConfig = ABSmartlyConfig()
absmartlyConfig.contextEventLogger = CustomEventLogger()
// OR, alternatively, during a particular context initialization
let contextConfig = ContextConfig()
contextConfig.eventLogger = CustomEventLogger()
The event data depends on the type of event. Currently, the SDK logs the following events:
event | when | data |
---|---|---|
error | Context receives an error | Error object |
ready | Context turns ready | ContextData used to initialize the context |
refresh | Context.refresh() method succeeds | ContextData used to refresh the context |
publish | Context.publish() method succeeds | PublishEvent sent to the ABsmartly event collector |
exposure | Context.getTreatment() method succeeds on first exposure | Exposure enqueued for publishing |
goal | Context.track() method succeeds | GoalAchievement enqueued for publishing |
close | Context.close() method succeeds the first time | nil |
The ABsmartly SDK can be instantiated with an event logger used for all contexts. The example below illustrates this with the implementation of the default event logger, used if none is specified.
Vue.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://sandbox-api.absmartly.com/v1",
apiKey: ABSMARTLY_API_KEY,
environment: "production",
application: "website",
eventLogger: (context, eventName, data) => {
if (eventName == "error") {
console.error(data);
}
},
},
/* ... */
});
The event data depends on the type of event. Currently, the SDK logs the following events:
eventName | when | data |
---|---|---|
"error" | Context receives an error | error object thrown |
"ready" | Context turns ready | data used to initialize the context |
"refresh" | Context.refresh() method succeeds | data used to refresh the context |
"publish" | Context.publish() method succeeds | data sent to the ABsmartly event collector |
"exposure" | Context.treatment() method succeeds on first exposure | exposure data enqueued for publishing |
"goal" | Context.track() method succeeds | goal data enqueued for publishing |
"finalize" | Context.finalize() method succeeds the first time | undefined |
The ABsmartly SDK can be instantiated with an event logger used for all contexts. The example below illustrates this with the implementation of the default event logger, used if none is specified.
Vue.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://sandbox-api.absmartly.com/v1",
apiKey: ABSMARTLY_API_KEY,
environment: "production",
application: "website",
eventLogger: (context, eventName, data) => {
if (eventName == "error") {
console.error(data);
}
},
},
/* ... */
});
The event data depends on the type of event. Currently, the SDK logs the following events:
eventName | when | data |
---|---|---|
"error" | Context receives an error | error object thrown |
"ready" | Context turns ready | data used to initialize the context |
"refresh" | Context.refresh() method succeeds | data used to refresh the context |
"publish" | Context.publish() method succeeds | data sent to the ABsmartly event collector |
"exposure" | Context.treatment() method succeeds on first exposure | exposure data enqueued for publishing |
"goal" | Context.track() method succeeds | goal data enqueued for publishing |
"finalize" | Context.finalize() method succeeds the first time | undefined |
The ABsmartly SDK can be instantiated with an event logger used for all
contexts. In addition, an event logger can be specified when creating a
particular context, in the ContextConfig
.
// example implementation
public class CustomEventLogger implements ContextEventLogger {
@Override
public void handleEvent(Context context, ContextEventLogger.EventType event, Object data) {
switch (event) {
case Exposure:
final Exposure exposure = (Exposure)data;
System.out.printf("exposed to experiment %s", exposure.name);
break;
case Goal:
final GoalAchievement goal = (GoalAchievement)data;
System.out.printf("goal tracked: %s", goal.name);
break;
case Error:
System.out.printf("error: %s", data);
break;
case Publish:
case Ready:
case Refresh:
case Close:
break;
}
}
}
// for all contexts, during sdk initialization
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create();
sdkConfig.setContextEventLogger(new CustomEventLogger());
// OR, alternatively, during a particular context initialization
final ContextConfig contextConfig = ContextConfig.create();
contextConfig.setEventLogger(new CustomEventLogger());
The data parameter depends on the type of event. Currently, the SDK logs the following events:
event | when | data |
---|---|---|
Error | Context receives an error | Throwable object |
Ready | Context turns ready | ContextData used to initialize the context |
Refresh | Context.refresh() method succeeds | ContextData used to refresh the context |
Publish | Context.publish() method succeeds | PublishEvent sent to the ABsmartly event collector |
Exposure | Context.getTreatment() method succeeds on first exposure | Exposure enqueued for publishing |
Goal | Context.track() method succeeds | GoalAchievement enqueued for publishing |
Close | Context.close() method succeeds the first time | null |
The ABsmartly SDK can be instantiated with an event logger used for all
contexts. In addition, an event logger can be specified when creating a
particular context, in the ContextConfig
.
type ContextEventLogger interface {
HandleEvent(context Context, types EventType, data interface{})
}
type EventType string
const (
Error EventType = "Error"
Ready EventType = "Ready"
Refresh EventType = "Refresh"
Publish EventType = "Publish"
Exposure EventType = "Exposure"
Goal EventType = "Goal"
Close EventType = "Close"
)
The data parameter depends on the type of event. Currently, the SDK logs the following events:
event | when | data |
---|---|---|
Error | Context receives an error | Throwable object |
Ready | Context turns ready | ContextData used to initialize the context |
Refresh | Context.refresh() method succeeds | ContextData used to refresh the context |
Publish | Context.publish() method succeeds | PublishEvent sent to the ABsmartly event collector |
Exposure | Context.getTreatment() method succeeds on first exposure | Exposure enqueued for publishing |
Goal | Context.track() method succeeds | GoalAchievement enqueued for publishing |
Close | Context.close() method succeeds the first time | null |
The ABsmartly SDK can be instantiated with an event logger used for all
contexts or, an event logger can be specified when creating a
particular context in the ContextConfig
.
// example implementation
public class CustomEventLogger : IContextEventLogger
{
public void HandleEvent(Context context, EventType eventType, object data)
{
switch (eventType)
{
case EventType.Exposure when data is Exposure exposure:
Console.WriteLine($"exposed to experiment: {exposure.Name}");
break;
case EventType.Goal when data is GoalAchievement goal:
Console.WriteLine($"goal tracked: {goal.Name}");
break;
case EventType.Error:
Console.WriteLine($"error: {data}");
break;
case EventType.Close:
case EventType.Publish:
case EventType.Ready:
case EventType.Refresh:
break;
}
}
}
// for all contexts, during SDK initialization
// when using dependency injection
builder.Services.AddABSmartly(
builder.Configuration.GetSection("ABSmartly"),
HttpClientConfig.CreateDefault(),
config => config.ContextEventLogger = new CustomEventLogger());
// or when creating SDK instance manually
var abSdk = new ABSdk(
new ABSdkHttpClientFactory(...),
new ABSmartlyServiceConfiguration {... },
new ABSdkConfig{ContextEventLogger = new CustomEventLogger()});
// OR, alternatively, during a particular context initialization
var contextConfig = new ContextConfig() {
ContextEventLogger = new CustomEventLogger()
};
The data parameter depends on the type of event. Currently, the SDK logs the following events:
event | when | data |
---|---|---|
Error | Context receives an error | Exception object |
Ready | Context turns ready | ContextData used to initialize the context |
Refresh | Context.Refresh() method succeeds | ContextData used to refresh the context |
Publish | Context.Publish() or Context.PublishAsync() method succeeds | PublishEvent sent to the ABsmartly event collector |
Exposure | Context.GetTreatment() method succeeds on first exposure | Exposure enqueued for publishing |
Goal | Context.Track() method succeeds | GoalAchievement enqueued for publishing |
Close | Context disposal succeeds | null |
The ABsmartly SDK can be instantiated with an event logger used for all contexts. In addition, an event logger can be specified when creating a particular context in the ContextConfig
.
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Context\ContextEventLoggerCallback;
$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(new ContextEventLoggerCallback(
function (string $event, ?object $data) {
// Custom callback
}
));
Alternately, it is possible to implement \ABSmartly\SDK\Context\ContextEventLogger
interface with handleEvent()
method that receives the Context
object itself, along with a ContextEventLoggerEvent
object as shown below:
use \ABSmartly\SDK\Context\ContextEventLoggerCallback;
class CustomLogger implements ContextEventLogger {
public function handleEvent(Context $context, ContextEventLoggerEvent $event): void {
// Process the log event
// e.g
// myLogFunction($event->getEvent(), $event->getData());
}
}
$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(CustomLogger());
The data parameter depends on the type of event. Currently, the SDK logs the following events:
eventName | when | data |
---|---|---|
"Error" | Context receives an error | Exception object thrown |
"Ready" | Context turns ready | ContextData object used to initialize the context |
"Refresh" | Context->refresh() method succeeds | ContextData used to refresh the context |
"Publish" | Context->publish() method succeeds | PublishEvent data sent to the ABsmartly event collector |
"Exposure" | Context->getTreatment() method succeeds on first exposure | Exposure data enqueued for publishing |
"Goal" | Context->Track() method succeeds | GoalAchivement goal data enqueued for publishing |
"Close" | Context->lose() method succeeds the first time | null |
The ABsmartly SDK can be instantiated with an event logger used for all contexts. In addition, an event logger can be specified when creating a particular context in the contextConfig
.
class CustomEventLogger implements ContextEventLogger {
void handleEvent(Context context, EventType event, dynamic data) {
switch (event) {
case EventType.Exposure:
final Exposure exposure = data;
print("exposed to experiment ${exposure.name}");
break;
case EventType.Goal:
final GoalAchievement goal = data;
print("goal tracked: ${goal.name}");
break;
case EventType.Error:
print("error: $data");
break;
case EventType.Publish:
case EventType.Ready:
case EventType.Refresh:
case EventType.Close:
break;
}
}
}
contextConfig.setContextEventLogger(CustomEventLogger());
The data parameter depends on the type of event. Currently, the SDK logs the following events:
eventName | when | data |
---|---|---|
"error" | Context receives an error | error object thrown |
"ready" | Context turns ready | data used to initialize the context |
"refresh" | Context.refresh() method succeeds | data used to refresh the context |
"publish" | Context.publish() method succeeds | data sent to the ABsmartly event collector |
"exposure" | Context.treatment() method succeeds on first exposure | exposure data enqueued for publishing |
"goal" | Context.track() method succeeds | goal data enqueued for publishing |
"finalize" | Context.finalize() method succeeds the first time | undefined |
Create a New Context Request
In order to start linking your experiments from the Web Console to your application, you will need to create a context. When you instantiate a context, you should pass all known characteristics of the current user. These characteristics are known as "units".
You can use anything as a unit. For example, you can pass an internal user id or
email address. You could also pass a device_id
that you store in a first-
party cookie or a mobile application UUID
.
The units that you pass must first be declared on your ABsmartly Web Console
by going to Settings -> Units
Experiments that are tracked by a unit which is not passed here will be turned off in this request and the control treatment will be shown instead.
- Javascript
- Python3
- React
- Swift
- Vue2
- Vue3
- Java
- Go
- .NET
- PHP
- Ruby
- Flutter/Dart
Create A New Context With Raw Promises
// define a new context request
const request = {
units: {
userId: "123",
session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8",
email: "[email protected]", // strings will be hashed
deviceId: "345",
},
};
const context = sdk.createContext(request);
context
.ready()
.then((response) => {
console.log("ABSmartly Context ready!");
})
.catch((error) => {
console.log(error);
});
Create A New Context With Async/Await
// define a new context request
const request = {
units: {
userId: "123",
session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8",
email: "[email protected]", // strings will be hashed
deviceId: "345",
},
};
const context = sdk.createContext(request);
try {
await context.ready();
console.log("ABSmartly Context ready!");
} catch (error) {
console.log(error);
}
Create A New Context With Pre-Fetched Data
When doing full-stack experimentation with ABsmartly, we recommend only creating a context once on the server-side. Creating a context involves a round-trip to the ABsmartly event collector. We can avoid repeating the round-trip on the client-side by sending the server-side data embedded in the first document, for example, by rendering it on the template. We can then initialize the ABsmartly context on the client-side directly with it.
// In your server-side code
const serverSideParams = {
units: {
user_id: '123',
anonymous_id: '456',
session_id: '789',
// ...
},
};
const serverSideContext = sdk.createContext(serverSideParams);
await serverSideContext.ready();
const serverSideData = serverSideContext.data();
// In your client-side code
const clientSideOptions = {
publishDelay: 100, // ms
};
const clientSideContext = sdk.createContextWith(serverSideParams, serverSideData, clientSideOptions);
Refreshing the Context with Fresh Experiment Data
For long-running single-page-applications (SPA), the context is usually created once when the application is first reached. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered. To mitigate this, we can use the refreshInterval option when creating the context.
const request = {
units: {
session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8",
},
};
const context = sdk.createContext(request, {
refreshInterval: 5 * 60 * 1000,
});
Alternatively, the refresh()
method can be called manually. The refresh()
method pulls updated experiment data from the ABsmartly collector and will
trigger recently started experiments when treatment()
is called again.
setTimeout(async () => {
try {
context.refresh();
} catch (error) {
console.error(error);
}
}, 5 * 60 * 1000);
HTTP request timeout
It is possible to set a timeout per individual HTTP request, overriding the global timeout set for all request when instantiating the SDK object.
Here is an example of setting a timeout only for the createContext
request.
const context = sdk.createContext(
request,
{
refreshInterval: 5 * 60 * 1000,
},
{
timeout: 1500,
}
);
HTTP Request cancellation
Sometimes it is useful to cancel an inflight HTTP request, for example, when
the user is navigating away. The ABsmartly SDK also supports a cancellation
via an AbortSignal
. An implementation of AbortController is provided for older
platforms, but will use the native implementation where available.
Here is an example of a cancellation scenario.
const controller = new absmartly.AbortController();
const context = sdk.createContext(
request,
{
refreshInterval: 5 * 60 * 1000,
},
{
signal: controller.signal,
}
);
// abort request if not ready after 1500ms
const timeoutId = setTimeout(() => controller.abort(), 1500);
await context.ready();
clearTimeout(timeoutId);
Synchronously
# define a new context request
context_config = ContextConfig()
context_config.publish_delay = 10
context_config.refresh_interval = 5
context_config = ContextConfig()
ctx = sdk.create_context(context_config)
ctx.wait_until_ready()
Asynchronously
# define a new context request
context_config = ContextConfig()
context_config.publish_delay = 10
context_config.refresh_interval = 5
context_config = ContextConfig()
ctx = sdk.create_context(context_config)
ctx.wait_until_ready_async()
With Prefetched Data
# define a new context request
context_config = ContextConfig()
context_config.publish_delay = 10
context_config.refresh_interval = 5
context_config.units = {"session_id": "bf06d8cb5d8137290c4abb64155584fbdb64d8",
"user_id": "12345"}
context_config = ContextConfig()
ctx = sdk.create_context(context_config)
ctx.wait_until_ready_async()
Refreshing the context with fresh experiment data
For long-running contexts, the context is usually created once when the application is first started.
However, any experiments being tracked in your production code, but started after the context was created, will not be triggered.
To mitigate this, we can use the set_refresh_interval()
method on the context config.
default_client_config = DefaultHTTPClientConfig()
default_client_config.refresh_interval = 5
Alternatively, the refresh()
method can be called manually.
The refresh()
method pulls updated experiment data from the ABsmartly
collector and will trigger recently started experiments when get_treatment()
is called.
context.refresh()
Setting extra units
You can add additional units to a context by calling the set_unit()
or the
set_units()
method. This method may be used for example, when a user logs in
to your application, and you want to use the new unit type to the context.
Please note that you cannot override an already set unit type as that
would be a change of identity, and will throw an exception. In this case, you
must create a new context instead. The SetUnit()
and SetUnits()
methods
can be called before the context is ready.
context.set_unit("db_user_id", "1000013")
context.set_units({
"db_user_id": "1000013"
})
The SDK's Provider component automatically creates a new context for you. This can be accessed in one of two ways:
Using React Hooks (Recommended)
import React, { useEffect } from "react";
import { useABSmartly } from "react-sdk";
function App() {
// Get the context object using the useABSmartly hook
const { context } = useABSmartly();
return (
<div className="App">
{
// ...App content
}
</div>
);
}
export default App;
Using withABSmartly
If you are unable to use React Hooks in your application, you can get access
to the context
object by wrapping your component in the withABSmartly
HOC
before exporting it.
import React from "react";
import { withABSmartly } from "react-sdk";
// The absmartly object comes from the withABSmartly HOC
function App({ absmartly }) {
const { context } = absmartly;
return (
<div className="App">
{
// ...App content
}
</div>
);
}
// Export the component wrapped in the withABSmartly HOC
export default withABSmartly(App);
Creating An Extra Context
If you need to create an extra context, you can do so by accessing the SDK object which is provided by both of the above methods.
const { context, sdk } = useABSmartly();
// or using the withABSmartly HOC
// const { context, sdk } = absmartly
const secondContext = sdk?.createContext({
units: {
user_id: "example_user_id",
anonymous_id: "example_anonymous_id",
},
});
Resetting the Context
Sometimes, it may be necessary to reset your context with a new set of units.
This can be done with the resetContext
function:
const { context, sdk, resetContext } = useABSmartly();
// or using the withABSmartly HOC
// const { context, sdk, resetContext } = absmartly
resetContext({
units: {
anonymous_id: "example_anonymous_id",
}
})
This can be useful when, for example, a user logs out and logs back in again.
You can then remove their user_id
and replace it with an anonymous_id
instead.
Creating a New Context
let contextConfig: ContextConfig = ContextConfig()
contextConfig.setUnit(unitType: "device_id", uid: UIDevice.current.identifierForVendor!.uuidString))
let context = sdk.createContext(config: contextConfig)
context.waitUntilReady().done { context in
print("context ready")
}
Creating a New Context With Pre-Fetched Data
When doing full-stack experimentation with ABsmartly, we recommend creating a context only once on the server-side. Creating a context involves a round-trip to the ABsmartly event collector. We can avoid repeating the round-trip on the client-side by sending the server-side data embedded with other application data. We can then initialize the ABsmartly context directly with it.
let contextConfig: ContextConfig = ContextConfig()
contextConfig.setUnit(unitType: "device_id", uid: UIDevice.current.identifierForVendor!.uuidString)
let context = sdk.createContextWithData(config: anotherContextConfig, contextData: contextData)
Setting Extra Units
You can add additional units to a context by calling the setUnit()
or
setUnits()
methods. These methods may be used, for example, when a user logs in
to your application and you want to use the new unit type in the context.
You cannot override an already set unit type as that would be a change of
identity, and would crash your application. In this case, you must create a new
context instead. The setUnit()
and setUnits()
methods can be called before
the context is ready.
context.setUnit(unitType: "db_user_id", uid: "1000013");
context.setUnits([
"db_user_id": "1000013"
]);
Refreshing the context with fresh experiment data
For long-running contexts, the context is usually created once when the
application is first reached. However, any experiments being tracked in your
production code, but started after the context was created, will not be
triggered. To mitigate this, we can use the setRefreshInterval()
method on the
context config.
let contextConfig: ContextConfig = ContextConfig()
contextConfig.setUnit(unitType: "device_id", uid: UIDevice.current.identifierForVendor!.uuidString)
contextConfig.refreshInterval = 4 * 3600; // every 4 hours
Alternatively, the refresh()
method can be called manually.
context.refresh().done {
print("refreshed")
}
Initializing with pre-fetched Context data
When doing full-stack experimentation with ABsmartly, we recommend creating a context only once on the server-side. Creating a context involves a round-trip to the ABsmartly event collector. We can avoid repeating the round-trip on the client-side by sending the server-side data embedded in the first document, for example, by rendering it on the template. Then we can initialize the ABsmartly context on the client-side directly with it. The Vue2 SDK also supports this optimized usage.
In this example, we assume the variable prefectedContextData
contains the
pre-fetched data previously injected.
// Somewhere in your application initialization code, before mounting your Vue application
Vue.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://sandbox-api.absmartly.com/v1",
apiKey: ABSMARTLY_API_KEY,
environment: "production",
application: "website",
},
context: {
units: {
session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8",
},
},
attributes: {
user_agent: navigator.userAgent,
},
data: prefetchedContext, // assuming prefectedContext has been injected
});
Refreshing the context with fresh experiment data
For long-running single-page-applications (SPA), the context is usually created once when the application is first reached. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered. To mitigate this, we can use the refreshInterval option when initializing the SDK.
Vue.use(absmartly.ABSmartlyVue, {
/* ... */
context: {
units: { session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8" },
refreshInterval: 5 * 60 * 1000,
},
/* ... */
});
Alternatively, the refresh()
method can be called manually. The refresh()
method pulls updated experiment data from the ABsmartly collector and will
trigger recently started experiments when treatment()
is called again.
setTimeout(async () => {
try {
this.$absmartly.refresh();
} catch (error) {
console.error(error);
}
}, 5 * 60 * 1000);
Synchronously
app.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: 'https://sandbox-api.absmartly.com/v1',
apiKey: ABSMARTLY_API_KEY,
environment: "production",
application: "website",
},
context: {
units: {
session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
},
},
attributes: {
user_agent: navigator.userAgent
},
});
With Prefetched Data
// somewhere in your application initialization code, before mounting your Vue application
app.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: 'https://sandbox-api.absmartly.com/v1',
apiKey: ABSMARTLY_API_KEY,
environment: "production",
application: "website",
},
context: {
units: {
session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
},
},
attributes: {
user_agent: navigator.userAgent
},
data: prefetchedContext, // assuming prefectedContext has been inject
});
Refreshing the Context with Fresh Experiment Data
For long-running contexts, the context is usually created once when the
application is first started. However, any experiments being tracked in your
production code, but started after the context was created, will not be
triggered. To mitigate this, we can use the refreshInterval
option on the
context config.
app.use(absmartly.ABSmartlyVue, {
/* ... */
context: {
units: { session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8" },
refreshInterval: 5 * 60 * 1000,
},
/* ... */
});
Alternatively, the refresh()
method can be called manually. The refresh()
method pulls updated experiment data from the ABsmartly collector and will
trigger recently started experiments when treatment()
is called again.
setTimeout(async () => {
try {
this.$absmartly.refresh();
} catch (error) {
console.error(error);
}
}, 5 * 60 * 1000);
Create A New Context Synchronously
// define a new context request
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"); // a unique id identifying the user
final Context context = sdk.createContext(contextConfig)
.waitUntilReady();
Create A New Context Asynchronously
// define a new context request
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"); // a unique id identifying the user
final Context context = sdk.createContext(contextConfig)
.waitUntilReadyAsync()
.thenAccept(ctx -> System.out.printf("context ready!"));
Create A New Context With Pre-Fetched Data
Creating a context involves a round-trip to the ABsmartly event collector. We can avoid repeating the round-trip on the client-side by re-using data previously retrieved.
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"); // a unique id identifying the user
final Context context = sdk.createContext(contextConfig)
.waitUntilReady();
final ContextConfig anotherContextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"); // a unique id identifying the other user
final Context anotherContext = sdk.createContextWith(anotherContextConfig, context.getData());
assert(anotherContext.isReady()); // no need to wait
Setting Extra Units
You can add additional units to a context by calling the setUnit()
or
setUnits()
methods. These methods may be used, for example, when a user logs in
to your application and you want to use the new unit type in the context.
You cannot override an already set unit type as that would be a change of
identity and would throw an exception. In this case, you must create a new
context instead. The setUnit()
and setUnits()
methods can be called before
the context is ready.
context.setUnit("db_user_id", "1000013");
context.setUnits(Map.of(
"db_user_id", "1000013"
));
Refreshing the context with fresh experiment data
For long-running contexts, the context is usually created once when the
application is first started. However, any experiments being tracked in your
production code, but started after the context was created, will not be
triggered. To mitigate this, we can use the setRefreshInterval()
method on the
context config.
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8")
.setRefreshInterval(TimeUnit.HOURS.toMillis(4)); // every 4 hours
Alternatively, the refresh()
method can be called manually. The refresh()
method pulls updated experiment data from the ABsmartly collector and will
trigger recently started experiments when getTreatment()
is called again.
context.refresh();
Create A New Context Synchronously
// define a new context request
var contextConfig = ContextConfig{Units_: map[string]string{
"session_id": "bf06d8cb5d8137290c4abb64155584fbdb64d8",
"user_id": "123456",
}}
var ctx = sdk.CreateContext(contextConfig)
ctx.WaitUntilReady()
Create A New Context Asynchronously
// define a new context request
var contextConfig = ContextConfig{Units_: map[string]string{
"session_id": "bf06d8cb5d8137290c4abb64155584fbdb64d8",
"user_id": "123456",
}}
var ctx = sdk.CreateContext(contextConfig)
ctx.WaitUntilReadyAsync()
Setting Extra Units
You can add additional units to a context by calling the SetUnit()
or the
SetUnits()
method. This method may be used for example, when a user logs in to
your application, and you want to use the new unit type to the context.
You cannot override an already set unit type as that would be a
change of identity, and will throw an exception. In this case, you must create
a new context instead. The SetUnit()
and SetUnits()
methods can be called
before the context is ready.
context.SetUnit("db_user_id", "1000013");
context.SetUnits(map[string]string{
"db_user_id": "1000013",
}
Refreshing the context with fresh experiment data
For long-running contexts, the context is usually created once when the
application is first started. However, any experiments being tracked in your
production code, but started after the context was created, will not be
triggered. To mitigate this, we can use the setRefreshInterval()
method on
the context config.
var contextConfig = ContextConfig{Units_: map[string]string{
"session_id": "bf06d8cb5d8137290c4abb64155584fbdb64d8",
"user_id": "123456",
}, RefreshInteval_: 4 * Time.Hour}
Alternatively, the Refresh()
method can be called manually. The Refresh()
method pulls updated experiment data from the ABsmartly collector and will
trigger recently started experiments when GetTreatment()
is called again.
context.Refresh();
Create A New Context Synchronously
// define a new context request
var config = new ContextConfig()
.SetUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8");
var context = await _abSdk.CreateContextAsync(config);
Create A New Context Asynchronously
// define a new context request
var config = new ContextConfig()
.SetUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8");
var context = _abSdk.CreateContext(config);
Creating A New Context With Pre-Fetched Data
Creating a context involves a round-trip to the ABsmartly event collector. We can avoid repeating the round-trip on the client-side by re-using previously retrieved data.
var config = new ContextConfig()
.SetUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8");
var context = await _abSdk.CreateContextAsync(config);
var anotherContextConfig = new ContextConfig()
.SetUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d9"); // a unique id identifying the other user
var anotherContext = _abSdk.CreateContextWith(anotherContextConfig, context.GetContextData());
Setting Extra Units
You can add additional units to a context by calling the SetUnit()
or the
SetUnits()
method. This method may be used for example, when a user logs in to
your application, and you want to add the new unit type to the context.
You cannot override an already set unit type as that would be a
change of identity, and will throw an exception. In this case, you must create
a new context instead. The SetUnit()
and SetUnits()
methods can be called
before the context is ready.
context.SetUnit("db_user_id", "1000013");
context.SetUnits(new Dictionary<string, string>() {
{ "db_user_id", "1000013" }
});
Refreshing The Context With Fresh Experiment Data
For long-running contexts, the context is usually created once when the
application is first started. However, any experiments being tracked in your
production code, but started after the context was created, will not be
triggered. To mitigate this, we can use the RefreshInterval()
method on
the context config.
var config = new ContextConfig()
.SetUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8");
config.RefreshInterval = TimeSpan.FromHours(4); // every 4 hours
Alternatively, the Refresh()
method can be called manually. The Refresh()
method pulls updated experiment data from the ABsmartly collector and will
trigger recently started experiments when GetTreatment()
is called again.
context.Refresh();
// or
await context.RefreshAsync();
Create A New Context Synchronously
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', 'session_id5ebf06d8cb5d8137290c4abb64155584fbdb64d8'); // a unique id identifying the user
$context = $sdk->createContext($contextConfig);
Create A Context With Prefetched Data
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', 'session_id5ebf06d8cb5d8137290c4abb64155584fbdb64d8'); // a unique id identifying the user
$context = $sdk->createContext($contextConfig);
$anotherContextConfig = new ContextConfig();
$anotherContextConfig->setUnit('session_id', 'session_id5ebf06d8cb5d8137290c4abb64155584fbdb64d8'); // a unique id identifying the user
$anotherContext = $sdk->createContextWithData($anotherContextConfig, $context->getContextData());
Refreshing the Context with Fresh Experiment Data
For long-running contexts, the context is usually created once when the application is first started. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered.
To mitigate this, we can use the Context->refresh()
method on the Context
.
$context->refresh();
The Context->refresh()
method pulls updated experiment data from the ABsmartly collector and will trigger recently started experiments when Context->getTreatment
is called again.
Setting Extra Units
You can add additional units to a context by calling the Context->setUnit
or Context->setUnits
methods. These methods may be used, for example, when a user logs in to your application, and you want to use the new unit type in the context.
Please note, you cannot override an already set unit type as that would be a change of identity and would throw an exception. In this case, you must create a new context instead. The Context->setUnit
and
Context->setUnits
methods can be called before the context is ready.
$context->setUnit('user_id', 143432);
Create A New Context
context_config = Absmartly.create_context_config
Create A Context With Prefetched Data
client_config = ClientConfig.new(
endpoint: 'https://your-company.absmartly.io/v1',
api_key: 'YOUR-API-KEY',
application: 'website',
environment: 'development')
sdk_config = ABSmartlyConfig.create
sdk_config.client = Client.create(client_config)
sdk = Absmartly.create(sdk_config)
Refreshing the context with fresh experiment data
For long-running contexts, the context is usually created once when the application is first started. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered.
Alternatively, the refresh
method can be called manually. The refresh
method
pulls updated experiment data from the ABsmartly collector and will trigger
recently started experiments when treatment
is called again.
Setting Extra Units
You can add additional units to a context by calling the set_unit()
or
set_units()
methods. These methods may be used, for example, when a user logs
in to your application and you want to use the new unit type in the context.
Please note, you cannot override an already set unit type as that would be a
change of identity and would throw an exception. In this case, you must
create a new context instead. The set_unit()
and set_units()
methods can be
called before the context is ready.
context_config.set_unit('session_id', 'bf06d8cb5d8137290c4abb64155584fbdb64d8')
context_config.set_unit('user_id', '123456')
context = Absmartly.create_context(context_config)
or
context_config.set_units(
session_id: 'bf06d8cb5d8137290c4abb64155584fbdb64d8',
user_id: '123456'
)
context = Absmartly.create_context(context_config)
Synchronously
createNewContext() async{
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"); // a unique id identifying the user
final Context? context = sdk.createContext(contextConfig)
.waitUntilReady();
if(context != null){
print("context ready");
}
}
Asynchronously
createNewContext() async{
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"); // a unique id identifying the user
final Context? context = await sdk.createContext(contextConfig)
.waitUntilReady();
if(context != null){
print("context ready");
}
}
With Prefetched Data
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"); // a unique id identifying the user
final Context context = sdk.createContext(contextConfig)
.waitUntilReady();
final ContextConfig anotherContextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"); // a unique id identifying the other user
final Context anotherContext = sdk.createContextWith(anotherContextConfig, context.getData());
assert(anotherContext.isReady()); // no need to wait
Refreshing the Context with Fresh Experiment Data
For long-running contexts, the context is usually created once when the application is first started. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered. To mitigate this, we can use the setRefreshInterval()
method on the context config.
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8")
.setRefreshInterval(TimeUnit.HOURS.toMillis(4)); // every 4 hours
Alternatively, the refresh()
method can be called manually. The refresh()
method pulls updated experiment data from the ABsmartly collector and will trigger recently started experiments when getTreatment()
is called again.
context.refresh()
Setting Extra Units
You can add additional units to a context by calling the setUnit()
or
setUnits()
methods. These methods may be used, for example, when a user
logs in to your application and you want to use the new unit type in the
context.
Please note, you cannot override an already set unit type as that would be
a change of identity and would throw an exception. In this case, you must
create a new context instead. The setUnit()
and
setUnits()
methods can be called before the context is ready.
context.setUnit("db_user_id", "1000013");
context.setUnits({
"db_user_id": "1000013"
});