# Example of implementation

This guide provides a practical use case example for implementing the Web Experimentation Resource Loader API. It demonstrates how to create a complete A/B test campaign with variations and modifications using a single API call.

### Overview

The Resource Loader API allows you to create, update, or delete multiple related resources (campaigns, variations, modifications, folders, audiences) in a single HTTP POST request. This approach ensures data consistency and simplifies the creation of complex experimentation setups.

### API Endpoint

```
POST https://resource-loader-api.abtasty.com/v1/web-exp/resource-loader
```

#### Headers

```http
Content-Type: application/json
Authorization: Bearer YOUR_API_TOKEN
```

### Use Case Example: Creating an A/B Test Campaign

This example demonstrates creating a complete A/B test setup that includes:

* A folder to organize campaigns
* An audience segment for targeting
* An A/B test campaign with two variations
* Modifications for each variation

#### Complete Resource Loader Payload

```json
{
  "version": 1,
  "resources": [
    {
      "type": "folder",
      "$_ref": "summer_folder",
      "action": "create",
      "payload": {
        "name": "Summer 2026 Campaigns"
      }
    },
    {
      "type": "audience",
      "$_ref": "returning_visitors",
      "action": "create",
      "payload": {
        "name": "Returning Visitors",
        "description": "Users who have visited more than once",
        "hidden": false,
        "allow_duplicated_config": true,
        "groups": [
          [
            {
              "operator": "auto",
              "mutation_observer": false,
              "type": "SESSION_NUMBER",
              "conditions": [
                {
                  "condition": 1,
                  "include": true,
                  "value": 2
                }
              ]
            }
          ]
        ]
      }
    },
    {
      "type": "campaign",
      "$_ref": "homepage_hero_test",
      "action": "create",
      "payload": {
        "name": "Homepage Hero Banner Test",
        "description": "Testing two different hero banner designs",
        "url": "https://example.com",
        "type": "ab",
        "status": "pause",
        "labels": ["homepage", "summer-2026"],
        "code": "console.log('Campaign initialized');",
        "folder_id": "$summer_folder.id",
        "campaign_targeting": {
          "segment_ids": ["$returning_visitors.id"],
          "url_scopes": [
            {
              "condition": "IS",
              "value": "https://example.com"
            }
          ],
          "targeting_frequency": {
            "type": "regular",
            "unit": "day",
            "value": 20
          }
        }
      },
      "resources": [
        {
          "type": "variation",
          "$_ref": "variant_a",
          "action": "create",
          "payload": {
            "name": "Variant A - New Design",
            "traffic": 14,
            "code": {
              "js": "console.log('Variant A loaded')",
              "css": "p {color: red; text-align: center;}"
            }
          },
          "resources": [
            {
              "type": "modification",
              "$_ref": "hero_text_change",
              "action": "create",
              "payload": {
                "name": "Update Hero Text",
                "selector": "#hero-banner h1",
                "type": "js",
                "code": "document.querySelector('#hero-banner h1').textContent = 'Summer Sale - Up to 50% Off!';"
              }
            }
          ]
        }
      ]
    }
  ]
}
```

### Step-by-Step Implementation

#### Step 1: Prepare Your Payload

Create a JSON file (e.g., `campaign-setup.json`) with your resource loader configuration. Use the `$_ref` notation to reference resources created earlier in the same request.

#### Step 2: Make the API Request

**Using cURL**

```bash
curl -X POST https://resource-loader-api.abtasty.com/v1/web-exp/resource-loader?account_id="<account_id>" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -d @campaign-setup.json
```

**Using JavaScript (Fetch API)**

```javascript
const resourceLoaderPayload = {
  version: 1,
  resources: [
    // Your resources here
  ],
};

fetch(
  "https://resource-loader-api.abtasty.com/v1/web-exp/resource-loader?account_id=123456",
  {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer YOUR_API_TOKEN",
    },
    body: JSON.stringify(resourceLoaderPayload),
  }
)
  .then((response) => response.json())
  .then((data) => {
    console.log("Success:", data);
  })
  .catch((error) => {
    console.error("Error:", error);
  });
```

#### Step 3: Handle the Response

The API will return a response containing the IDs of all created resources:

```json
{
  "status": "success",
  "results": [
    {
      "$_ref": "summer_folder",
      "status": "success",
      "response": {
        "id": "folder_abc123",
        "name": "Summer 2026 Campaigns"
      }
    },
    {
      "$_ref": "returning_visitors",
      "status": "success",
      "response": {
        "id": "audience_xyz789",
        "name": "Returning Visitors"
      }
    },
    {
      "$_ref": "homepage_hero_test",
      "status": "success",
      "response": {
        "id": "campaign_def456",
        "name": "Homepage Hero Banner Test",
        "status": "pause"
      }
    }
    // Additional results for variations and modifications...
  ]
}
```

### Advanced Use Cases

#### Updating Existing Resources

To update an existing campaign, use the `update` action and provide the resource ID:

```json
{
  "version": 1,
  "resources": [
    {
      "type": "campaign",
      "$_ref": "update_campaign",
      "action": "edit",
      "payload": {
        "id": "campaign_def456",
        "status": "play",
        "description": "Updated description"
      }
    }
  ]
}
```

#### Deleting Resources

To delete a resource:

```json
{
  "version": 1,
  "resources": [
    {
      "type": "modification",
      "$_ref": "delete_mod",
      "action": "delete",
      "id": "modification_ghi789"
    }
  ]
}
```

#### Using Reference Injection

You can inject existing resource IDs from command-line flags when using the AB Tasty CLI:

```bash
abtasty web-experimentation resource load \
  --file campaign-setup.json \
  --input-ref '{"existing_folder":"folder_abc123"}'
```

Then reference it in your JSON:

```json
{
  "type": "campaign",
  "payload": {
    "folder_id": "$existing_folder"
  }
}
```

### Best Practices

1. **Use Meaningful References**: Choose descriptive `$_ref` names that clearly indicate what each resource represents.
2. **Organize Hierarchically**: Structure your resources in parent-child relationships using the nested `resources` array for better readability.
3. **Test with Paused Status**: Always create campaigns with `"status": "pause"` initially, then activate them after verification.
4. **Validate Before Sending**: Ensure all required fields are present and references are correct to avoid partial failures.
5. **Handle Errors Gracefully**: Check the response status for each resource, as some may succeed while others fail.
6. **Use Folders for Organization**: Group related campaigns in folders for easier management.
7. **Start Simple**: Begin with a small test payload before creating complex nested structures.

### Support

For questions or issues with the Resource Loader API, consult the main [Resource Loader documentation](/server-side/command-line-interface/resource-loader.md) or contact AB Tasty support.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.abtasty.com/server-side/command-line-interface/resource-loader/web-experimentation/example-of-implementation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
