# Getting Started

This page walks you through connecting your application to ABsmartly. By the end, you'll have the SDK installed, initialised, and a context ready to use for experiments.

Once you've finished here, the [next page](https://docs.absmartly.com/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.md) walks through a complete experiment: assigning variants, reading variables, and tracking goals. Together, these two pages give you everything you need to run your first test.

> **Prerequisites**
>
> Before you start, make sure you have:
>
> * An ABsmartly account with your Web Console set up
> * Your **API key** (found in Settings > API Keys in the Web Console)
> * Your **application name** and **environment** configured in the Web Console

## 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**

```bash
npm install --save @absmartly/javascript-sdk
```

**Other installation methods**

**Direct Import**

```html
<script src="https://unpkg.com/@absmartly/javascript-sdk/dist/absmartly.min.js"></script>
```

> **caution**
>
> ABsmartly’s Javascript SDK depends on support for a native ES6 promise implementation. If your environment does not support ES6 promises, you can [polyfill](https://github.com/stefanpenner/es6-promise).

**Python3**

```bash
pip install absmartly
```

**Compatibility and dependencies**

The ABsmartly Python SDK is compatible with Python 3. It provides both a blocking and an asynchronous interface.

**Dependencies:**

* `setuptools~=60.2.0`
* `requests~=2.28.1`
* `urllib3~=1.26.12`
* `jsons~=1.6.3`

**React**

```bash
npm install --save @absmartly/react-sdk
```

**Server-side rendering**

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**

**Swift Package Manager**

1. In Xcode go to: `File -> Swift Packages -> Add Package Dependency...`
2. Enter the ABsmartly Swift SDK GitHub repository: <https://github.com/absmartly/swift-sdk>
3. Select the SDK version (latest recommended)
4. Select the ABSmartly library

**Using CocoaPods instead**

Add the following lines to your `Podfile`:

```ruby
pod 'ABSmartlySwiftSDK'
```

Run the following command to update your Xcode project:

```bash
pod install
```

**Vue2**

```bash
npm install --save @absmartly/vue2-sdk
```

**Direct import via CDN**

Add the following to your `head` section to include the latest published version from [unpkg.com](https://unpkg.com):

```html
<script src="https://unpkg.com/@absmartly/vue2-sdk"></script>
```

**Vue3**

```bash
npm install --save @absmartly/vue3-sdk
```

**Direct import via CDN**

Add the following to your `head` section to include the latest published version from [unpkg.com](https://unpkg.com):

```html
<script src="https://unpkg.com/@absmartly/vue3-sdk"></script>
```

**Java**

**Gradle**

Replace {VERSION} with the latest SDK version available in MavenCentral.

```gradle
dependencies {
  implementation 'com.absmartly.sdk:core-api:{VERSION}'
}
```

**Using Maven instead**

Replace {VERSION} with the latest SDK version available in MavenCentral.

```xml
<dependency>
  <groupId>com.absmartly.sdk</groupId>
  <artifactId>core-api</artifactId>
  <version>{VERSION}</version>
</dependency>
```

**Compatibility and Android support**

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](https://github.com/stefan-zobel/streamsupport) 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:

```xml
<uses-permission android:name="android.permission.INTERNET"/>
```

> **Android 6.0 or earlier**
>
> When targeting Android 6.0 or earlier, the default Java Security Provider will not work. Using [Conscrypt](https://github.com/google/conscrypt) is recommended. Follow [these instructions](https://github.com/google/conscrypt/blob/master/README.md) to install it as dependency.

**Go**

```go-module
require github.com/absmartly/go-sdk
```

```bash
sh ./run.sh
```

**Compatibility**

The ABsmartly Go SDK is compatible with Go versions 1.15 and later. It provides both a blocking and an asynchronous interface.

**.NET**

```bash
  dotnet add package ABSmartly.Sdk
```

**Compatibility**

The .NET SDK targets **.NET Standard 2.0** and **.NET 5**, but is also fully compatible with **.NET 6**.

**PHP**

```bash
composer require absmartly/php-sdk
```

**Compatibility**

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.

**Ruby**

```bash
bundle add absmartly
```

**Installing without Bundler**

```bash
gem install absmartly
```

**Compatibility**

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.

**Flutter/Dart**

*pubspec.yaml*

```yaml
    absmartly_sdk: ^version
```

**Compatibility**

The ABsmartly Flutter SDK is compatible with Dart versions 2.18.6 and later.

## Import and Initialise the SDK

**Javascript**

```js
import absmartly from "@absmartly/javascript-sdk";

const sdk = new absmartly.SDK({
  endpoint: "https://your-company.absmartly.io/v1",
  apiKey: "YOUR-API-KEY",
  environment: "production",
  application: "website",
});
```

**Python3**

The Python SDK separates client and SDK configuration so you can swap the HTTP client implementation if needed.

```python
client_config = ClientConfig()
client_config.endpoint = "https://your-company.absmartly.io/v1"
client_config.api_key = "YOUR-API-KEY"
client_config.application = "website"
client_config.environment = "production"

sdk_config = ABSmartlyConfig()
sdk_config.client = Client(client_config, DefaultHTTPClient(DefaultHTTPClientConfig()))
sdk = ABSmartly(sdk_config)
```

**React**

The React SDK wraps your app in a Provider that handles both SDK initialisation and context creation in one step:

```jsx
import ABSmartly from "@absmartly/react-sdk";

function App() {
  return (
    <ABSmartly
      sdkOptions={{
        endpoint: "https://your-company.absmartly.io/v1",
        apiKey: "YOUR-API-KEY",
        environment: "production",
        application: "website",
      }}
      contextOptions={{
        units: { user_id: "user-12345" },
      }}
    >
      {/* Your app content */}
    </ABSmartly>
  );
}
```

> **note**
>
> The `<ABSmartly>` Provider creates a context automatically. You can skip ahead to [Next steps](#next-steps) and access the context in any child component with the `useABSmartly()` hook.

**Swift**

```swift
import ABSmartly

let clientConfig = ClientConfig(
    apiKey: "YOUR-API-KEY",
    application: "website",
    endpoint: "https://your-company.absmartly.io/v1",
    environment: "production")

let client = try DefaultClient(config: clientConfig)
let sdkConfig = ABSmartlyConfig(client: client)
let sdk = try ABSmartlySDK(config: sdkConfig)
```

**Vue2**

The Vue2 SDK initialises as a plugin, creating both the SDK and a context in one step. This makes the `$absmartly` extension available in every Vue instance.

```js
import absmartly from "@absmartly/vue2-sdk";

Vue.use(absmartly.ABSmartlyVue, {
  sdkOptions: {
    endpoint: "https://your-company.absmartly.io/v1",
    apiKey: "YOUR-API-KEY",
    environment: "production",
    application: "website",
  },
  context: {
    units: {
      user_id: "user-12345",
    },
  },
});
```

> **note**
>
> The plugin creates a context automatically. You can skip ahead to [Next steps](#next-steps) and access it via `this.$absmartly` in any component.

**Passing attributes and overrides at init**

You can also pass context attributes and overrides during plugin initialisation:

```js
Vue.use(absmartly.ABSmartlyVue, {
  sdkOptions: {
    endpoint: "https://your-company.absmartly.io/v1",
    apiKey: "YOUR-API-KEY",
    environment: "production",
    application: "website",
  },
  context: {
    units: {
      user_id: "user-12345",
    },
  },
  attributes: {
    user_agent: navigator.userAgent,
  },
  overrides: {
    exp_test_development: 1,
  },
});
```

**Using pre-fetched context data**

If you have already fetched context data on the server (see [Pre-Fetching Context Data](https://docs.absmartly.com/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data.md)), you can pass it directly to avoid an extra network request:

```js
Vue.use(absmartly.ABSmartlyVue, {
  sdkOptions: {
    endpoint: "https://your-company.absmartly.io/v1",
    apiKey: "YOUR-API-KEY",
    environment: "production",
    application: "website",
  },
  context: {
    units: {
      user_id: "user-12345",
    },
  },
  data: prefetchedContext,
});
```

**Vue3**

The Vue3 SDK initialises as a plugin, creating both the SDK and a context in one step. This makes the `$absmartly` extension available in every Vue instance.

```js
import absmartly from "@absmartly/vue3-sdk";

app.use(absmartly.ABSmartlyVue, {
  sdkOptions: {
    endpoint: "https://your-company.absmartly.io/v1",
    apiKey: "YOUR-API-KEY",
    environment: "production",
    application: "website",
  },
  context: {
    units: {
      user_id: "user-12345",
    },
  },
});
```

> **note**
>
> The plugin creates a context automatically. You can skip ahead to [Next steps](#next-steps) and access it via `this.$absmartly` in any component.

**Passing attributes and overrides at init**

You can also pass context attributes and overrides during plugin initialisation:

```js
app.use(absmartly.ABSmartlyVue, {
  sdkOptions: {
    endpoint: "https://your-company.absmartly.io/v1",
    apiKey: "YOUR-API-KEY",
    environment: "production",
    application: "website",
  },
  context: {
    units: {
      user_id: "user-12345",
    },
  },
  attributes: {
    user_agent: navigator.userAgent,
  },
  overrides: {
    exp_test_development: 1,
  },
});
```

**Using pre-fetched context data**

If you have already fetched context data on the server (see [Pre-Fetching Context Data](https://docs.absmartly.com/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data.md)), you can pass it directly to avoid an extra network request:

```js
app.use(absmartly.ABSmartlyVue, {
  sdkOptions: {
    endpoint: "https://your-company.absmartly.io/v1",
    apiKey: "YOUR-API-KEY",
    environment: "production",
    application: "website",
  },
  context: {
    units: {
      user_id: "user-12345",
    },
  },
  data: prefetchedContext,
});
```

**Java**

```java
final ClientConfig clientConfig = ClientConfig.create()
    .setEndpoint("https://your-company.absmartly.io/v1")
    .setAPIKey("YOUR-API-KEY")
    .setApplication("website")
    .setEnvironment("production");

final Client absmartlyClient = Client.create(clientConfig);

final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
    .setClient(absmartlyClient);

final ABSmartly sdk = ABSmartly.create(sdkConfig);
```

**Targeting Android 6.0 or earlier**

When targeting Android 6.0 or earlier, set the default Java Security Provider for SSL to Conscrypt by creating the Client instance as follows:

```java
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")
    .setEnvironment("production");

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);
```

**Go**

```go
clientConfig := ClientConfig{
    Endpoint_:    "https://your-company.absmartly.io/v1",
    ApiKey_:      "YOUR-API-KEY",
    Application_: "website",
    Environment_: "production",
}

sdkConfig := ABSmartlyConfig{Client_: CreateDefaultClient(clientConfig)}
sdk := Create(sdkConfig)
```

**.NET**

If your project uses dependency injection, register the SDK in your startup code:

```csharp
builder.Services.AddABSmartly(
    builder.Configuration.GetSection("ABSmartly"),
    HttpClientConfig.CreateDefault());
```

*appsettings.json*

```json
{
  "ABSmartly": {
    "Environment": "production",
    "Application": "website",
    "Endpoint": "https://your-company.absmartly.io/v1",
    "ApiKey": "YOUR-API-KEY"
  }
}
```

The `ABSdk` instance is registered as a singleton and can be injected into any controller or service:

```csharp
[ApiController]
[Route("[controller]")]
public class Test : ControllerBase
{
    private readonly ABSdk _abSdk;

    public Test(ABSdk abSdk)
    {
        _abSdk = abSdk;
    }
}
```

**Advanced DI configuration (Polly, custom HTTP clients)**

The `AddABSmartly` extension method also allows you to configure HTTP connection settings, inject custom implementations of context-specific services, and configure additional HTTP request policies using [Polly](https://github.com/App-vNext/Polly).

If you need a custom `IHttpClientFactory` implementation, make sure it creates named `IHttpClient` instances with the name `ABSmartlySDK.HttpClient` (available as the static field `ABSdk.HttpClientName`).

**Manual instantiation (without dependency injection)**

```csharp
var serviceProvider = new ServiceCollection()
    .AddHttpClient()
    .BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();

var sdk = new ABSdk(
    new ABSdkHttpClientFactory(httpClientFactory),
    new ABSmartlyServiceConfiguration
    {
        Environment = "production",
        Application = "website",
        Endpoint = "https://your-company.absmartly.io/v1",
        ApiKey = "YOUR-API-KEY"
    });
```

**PHP**

```php
use \ABSmartly\SDK\SDK;

$sdk = SDK::createWithDefaults(
    endpoint: 'https://your-company.absmartly.io/v1',
    apiKey: 'YOUR-API-KEY',
    environment: 'production',
    application: 'website',
);
```

> **note**
>
> The example above uses named parameters (PHP 8.0+). On PHP 7.4, pass the parameters in order instead:
>
> ```php
> $sdk = SDK::createWithDefaults(
>   'https://your-company.absmartly.io/v1', 'YOUR-API-KEY', 'production', 'website',
> );
> ```

**Granular component setup (custom event logger, etc.)**

The `createWithDefaults` shortcut works for most cases. If you need finer control over individual components (for example, to inject a custom event logger), build the SDK from its parts instead:

```php
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(
    'https://your-company.absmartly.io/v1',
    'YOUR-API-KEY',
    'website',
    'production'
);
$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);
```

**Ruby**

```ruby
Absmartly.configure_client do |config|
  config.endpoint = "https://your-company.absmartly.io/v1"
  config.api_key = "YOUR-API-KEY"
  config.application = "website"
  config.environment = "production"
end
```

**Flutter/Dart**

```dart
final ClientConfig clientConfig = ClientConfig()
  ..setEndpoint("https://your-company.absmartly.io/v1")
  ..setAPIKey("YOUR-API-KEY")
  ..setApplication("website")
  ..setEnvironment("production");

final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
    .setClient(Client.create(clientConfig));
final ABSmartly sdk = ABSmartly(sdkConfig);
```

Every SDK requires four options:

| Option        | Description                                                                                    |
| ------------- | ---------------------------------------------------------------------------------------------- |
| `endpoint`    | Your API endpoint URL. Typically `https://your-company.absmartly.io/v1`                        |
| `apiKey`      | Found in Settings > API Keys in the Web Console                                                |
| `environment` | Must match an environment configured in the Web Console (e.g. `"production"`, `"development"`) |
| `application` | Must match an application configured in the Web Console                                        |

**Optional configuration**

Beyond the four required options, every SDK also accepts these optional settings:

| Option        | Default   | Description                                                                                                                              |
| ------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `retries`     | `5`       | Number of retries before the SDK stops trying to connect                                                                                 |
| `timeout`     | `3000` ms | How long to wait for a response before giving up                                                                                         |
| `eventLogger` | none      | Callback that fires on SDK events (exposures, goals, errors). See the [custom event logger](#using-a-custom-event-logger) section below. |

> **Language-specific differences**
>
> Most SDKs use the names and defaults above. A few differ:
>
> * **Python**: `max_retries`, `connection_timeout` (in seconds, not milliseconds), `context_event_logger`
> * **Swift**: `retries` defaults to `3` (not `5`). Timeouts are in seconds, not milliseconds.
> * **PHP**: `retries` and `timeout` are `int` types. The event logger accepts a `ContextEventLoggerCallback` or any `ContextEventLogger` implementation.
> * **Flutter/Dart**: Does not expose `retries`, `timeout`, or `eventLogger` as top-level options. These are configured through the client config.

**Using a custom event logger**

The SDK fires events internally for things like exposures and goal tracking. By default these are handled automatically, but you can plug in a custom event logger if you need to:

* **Debug during development** by printing events to the console
* **Send events to your own analytics pipeline** alongside ABsmartly's collector
* **Monitor SDK behaviour in production** for observability

The SDK can be instantiated with an event logger used for all contexts. In addition, most SDKs let you specify an event logger per context when calling `createContext`.

The event logger receives events with a data payload that depends on the event type. The SDK fires the following events:

| Event            | When                                     | Data                                         |
| ---------------- | ---------------------------------------- | -------------------------------------------- |
| error            | `Context` receives an error              | Error/exception object                       |
| ready            | `Context` turns ready                    | `ContextData` used to initialize the context |
| refresh          | `refresh()` succeeds                     | `ContextData` used to refresh the context    |
| publish          | `publish()` succeeds                     | Event data sent to the ABsmartly collector   |
| exposure         | `treatment()` succeeds on first exposure | Exposure data enqueued for publishing        |
| goal             | `track()` succeeds                       | Goal data enqueued for publishing            |
| close / finalize | Context is closed or finalized           | `null` / `undefined`                         |

> **Naming differences**
>
> Javascript, React, Vue, and Flutter use `"finalize"` for the close event. Python, Java, Go, Swift, .NET, PHP, and Ruby use `"close"`. The method and event names in the code examples below match each SDK's convention.

**Javascript**

```js
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);
    }
  },
});
```

**Python3**

```py
    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
```

**React**

```jsx
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")
);
```

**Swift**

```swift
// 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()
```

**Vue2**

```js
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);
      }
    },
  },
  /* ... */
});
```

**Vue3**

```js
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);
      }
    },
  },
  /* ... */
});
```

**Java**

```java
    // 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());
```

**Go**

```go
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"
)
```

**.NET**

```csharp
    // 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;
            }
        }
    }
```

With dependency injection:

```csharp
    // 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()
    };
```

**PHP**

```php
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Context\ContextEventLoggerCallback;

$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(new ContextEventLoggerCallback(
    function (string $event, ?object $data) {
        // Custom callback
    }
));
```

Alternatively, you can implement the `\ABSmartly\SDK\Context\ContextEventLogger` interface with a `handleEvent()` method that receives the `Context` object and a `ContextEventLoggerEvent`:

```php
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());
```

**Ruby**

```ruby
class CustomEventLogger < ContextEventLogger
  def handle_event(event, data)
    case event
    when EVENT_TYPE::EXPOSURE
      puts "Exposure: #{data}"
    when EVENT_TYPE::GOAL
      puts "Goal: #{data}"
    when EVENT_TYPE::ERROR
      puts "Error: #{data}"
    when EVENT_TYPE::PUBLISH
      puts "Publish: #{data}"
    when EVENT_TYPE::READY
      puts "Ready: #{data}"
    when EVENT_TYPE::REFRESH
      puts "Refresh: #{data}"
    when EVENT_TYPE::CLOSE
      puts "Close"
    end
  end
end

# For all contexts, during SDK initialization
Absmartly.configure_client do |config|
  config.endpoint = "https://your-company.absmartly.io/v1"
  config.api_key = "YOUR-API-KEY"
  config.application = "website"
  config.environment = "production"
  config.event_logger = CustomEventLogger.new
end

# OR, for a particular context
context_config = Absmartly.create_context_config
context_config.set_event_logger(CustomEventLogger.new)
```

**Flutter/Dart**

```dart
class CustomEventLogger implements ContextEventLogger {
  @override
  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;
    }
  }
}
```

```dart
    contextConfig.setContextEventLogger(CustomEventLogger());
```

## Create a New Context Request

A context represents a single user's session with ABsmartly. It holds their variant assignments and queues up events to send to the collector. You'll need to create one before you can check treatments or track goals.

**Javascript**

```js
const context = sdk.createContext({
  units: {
    user_id: "user-12345",
  },
});

await context.ready();
```

**Using promises instead of async/await**

If you're not in an async context, you can use the promise-based API:

```js
const context = sdk.createContext({
  units: {
    user_id: "user-12345",
  },
});

context.ready().then(() => {
  const variant = context.treatment("experiment_name");
});
```

**Python3**

```python
context_config = ContextConfig()
context_config.units = {"user_id": "user-12345"}

ctx = sdk.create_context(context_config)
ctx.wait_until_ready()
```

**React**

The `<ABSmartly>` Provider already created a context during initialisation. Access it in any child component with the `useABSmartly()` hook:

```jsx
import { useABSmartly } from "@absmartly/react-sdk";

function MyComponent() {
  const { context } = useABSmartly();
  // context is ready to use
}
```

**Using class components**

If your codebase uses class components, the SDK also exports a `withABSmartly` higher-order component that provides the context as a prop:

```jsx
import { withABSmartly } from "@absmartly/react-sdk";

function App({ absmartly }) {
  const { context } = absmartly;

  return <div>{/* Your app content */}</div>;
}

export default withABSmartly(App);
```

**Swift**

```swift
let contextConfig = ContextConfig()
contextConfig.setUnit(unitType: "user_id", uid: "user-12345")

let context = sdk.createContext(config: contextConfig)
context.waitUntilReady()
```

**Vue2**

The plugin already created a context during initialisation. Access it in any component via `this.$absmartly`:

```js
export default {
  mounted() {
    const treatment = this.$absmartly.treatment("experiment_name");
  },
};
```

**Vue3**

The plugin already created a context during initialisation. Access it in any component via `this.$absmartly`:

```js
export default {
  mounted() {
    const treatment = this.$absmartly.treatment("experiment_name");
  },
};
```

**Java**

```java
final ContextConfig contextConfig = ContextConfig.create()
    .setUnit("user_id", "user-12345");

final Context context = sdk.createContext(contextConfig)
    .waitUntilReady();
```

**Go**

```go
contextConfig := ContextConfig{
    Units_: map[string]string{
        "user_id": "user-12345",
    },
}

ctx := sdk.CreateContext(contextConfig)
ctx.WaitUntilReady()
```

**.NET**

```csharp
var config = new ContextConfig()
    .SetUnit("user_id", "user-12345");

var context = await sdk.CreateContextAsync(config);
```

**PHP**

```php
$contextConfig = new ContextConfig();
$contextConfig->setUnit('user_id', 'user-12345');

$context = $sdk->createContext($contextConfig);
```

**Ruby**

```ruby
context_config = Absmartly.create_context_config
context_config.unit("user_id", "user-12345")

context = Absmartly.create_context(context_config)
```

**Flutter/Dart**

```dart
final ContextConfig contextConfig = ContextConfig.create()
    .setUnit("user_id", "user-12345");

final Context? context = sdk.createContext(contextConfig)
    .waitUntilReady();
```

> **info**
>
> The `user_id` above is just an example. You can use any unit type that you've configured in your Web Console under Settings > Units (e.g. `session_id`, `device_id`, `email`). Pass all the units you have available for the current user. If you're not sure which ones to use, check Settings > Units in the Web Console. You'll see how these connect to experiments on the [next page](https://docs.absmartly.com/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.md).

## Next steps

Your SDK is installed, initialised, and you have a context ready to go. Head over to [Running Your First Experiment](https://docs.absmartly.com/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.md) to learn how to assign variants, use variables, and track goals.
