> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 実験から JS と CSS コードを取得する

> Automation API を使用して、一時停止または停止された実験の勝者バリエーションから JavaScript と CSS コードを取得します。

このガイドでは、2026 年以降に一時停止または停止された Developer（コードベース）実験の勝者バリエーションから JavaScript と CSS コードを取得する方法を説明します。

コードを取得するには、次の手順を完了します:

1. [フィルタを構築](#フィルタを構築する) して、2026 年以降に一時停止または停止されたコードベースの実験を取得します。
2. [Get all experiments エンドポイント](/api-reference/experiment/get-all-experiments) を使用して [フィルタした実験を取得](#フィルタした実験を取得する) します。
3. [実験結果を取得](./retrieving-experiment-results-using-the-automation-api) して [勝者のバリエーションを特定](#勝者のバリエーションを見つける) します。
4. [Get a variation エンドポイント](/api-reference/variation/get-a-variation) を使用して [JS と CSS コードを取得](#js-と-css-コードを取得する) します。

ガイドの最後には、ワークフローを実装した [完全な Python スクリプト](#完全な-python-スクリプト) もあります。

## 前提条件

Automation API を使用する前に、アクセストークンを取得していることを確認してください。

トークンの取得方法については、[認証ガイド](/developer-docs/apis/automation-api-rest/get-started/get-started#1-obtain-an-access-token) を参照してください。

## フィルタを構築する

実験をフィルタするには、`filter` クエリパラメータを使用します。次の基準に基づいて実験をフィルタします:

* `status`: `PAUSED` または `STOPPED` に設定。
* `dateStatusModified`: 2026 年 1 月 1 日より大きい値に設定。
* `type`: `DEVELOPER` に設定。

### フィルタの例

```json theme={null}
[
  {
    "field": "status",
    "operator": "IN",
    "parameters": ["PAUSED", "STOPPED"]
  },
  {
    "field": "dateStatusModified",
    "operator": "GREATER",
    "parameters": ["2026-01-01T00:00:00"]
  },
  {
    "field": "type",
    "operator": "IN",
    "parameters": ["DEVELOPER"]
  }
]
```

<Tip>
  Experiment ダッシュボードから有効なフィルタを直接生成するには:

  1. [Experiment ダッシュボード](/user-manual/experimentation/web-experimentation/manage-your-web-experiments/manage-your-experiments#access-the-experiments-dashboard) を開きます。
  2. ダッシュボードの UI を使用して希望のフィルタを適用します。
  3. ブラウザの **Developer Tools** を開きます。
  4. **Network** タブに移動します。
  5. `GetExperiments` リクエストを検索します。
  6. 対応する **GraphQL** リクエストを開き、**Payload** タブを選択します。

  インターフェースが生成した正確なフィルタ設定をコピーして、Automation API で再利用できます。

  <Frame>
    ![GraphQL filter example](https://storage.googleapis.com/kameleoon-storage-documentation/developers/images/apis/automation-api-rest/tutorials/retrieve-js-and-css-code-from-experiments/filter-graphql.png)
  </Frame>
</Tip>

## フィルタした実験を取得する

フィルタを URL クエリパラメータとして渡します。URL に追加する前に、JSON フィルタをパーセントエンコードしてください。

### リクエスト例

```bash theme={null}
curl -L "https://api.kameleoon.com/experiments?filter=%5B%7B%22field%22%3A%22status%22%2C%22operator%22%3A%22IN%22%2C%22parameters%22%3A%5B%22PAUSED%22%2C%22STOPPED%22%5D%7D%2C%7B%22field%22%3A%22dateStatusModified%22%2C%22operator%22%3A%22GREATER%22%2C%22parameters%22%3A%5B%222026-01-01T00%3A00%3A00%22%5D%7D%2C%7B%22field%22%3A%22type%22%2C%22operator%22%3A%22IN%22%2C%22parameters%22%3A%5B%22DEVELOPER%22%5D%7D%5D" \
-H "Accept: */*" \
-H "Authorization: Bearer <ACCESS_TOKEN>"
```

### レスポンス例

```json theme={null}
[
  {
    "id": 344428,
    "siteId": 31553,
    "name": "TestJavascriptHelpDoc",
    "type": "DEVELOPER",
    "status": "STOPPED",
    "mainGoalId": 396889,
    "variations": [1199120, 1199121],
    "dateStatusModified": "2026-02-09T11:23:31+0100",
    "commonJavaScriptCode": "console.log(\"hello world\");",
    "globalScript": "console.log(\"hello world\");"
  }
]
```

このレスポンスから、次の手順で使用する以下のフィールドをメモします:

* `id`: 実験 ID。
* `mainGoalId`: 実験結果を取得するために必要です。
* `variations`: バリエーション ID のリスト。

***

## 勝者のバリエーションを見つける

勝者のバリエーションを特定するには、次の手順を完了します:

1. 実験結果を取得します。詳細については [実験結果を取得する](./retrieving-experiment-results-using-the-automation-api) を参照してください。
2. 前のレスポンスから `mainGoalId` を含めます。
3. 各バリエーションの `improvementRate` を比較します。

### リクエスト例

```bash theme={null}
curl -L -X POST "https://api.kameleoon.com/experiments/344428/results" \
-H "Content-Type: application/json" \
-H "Accept: */*" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
--data-raw '{
  "visitorData": false,
  "sequentialTesting": true,
  "referenceVariationId": "0",
  "goalsIds": [396889]
}'
```

### レスポンス

リクエストを送信すると、データコードを受け取ります。このコードを使用して結果を取得します。詳細については、[実験結果取得ガイド](./retrieving-experiment-results-using-the-automation-api) を参照してください。

### 勝者を特定する

レスポンスデータから、`_reference`（ベースライン）バリエーションを除く各バリエーション ID（たとえば `1199120` および `1199121`）の `goalsData` を特定します。

各バリエーションの `improvementRate` を比較します。最も正の `improvementRate` が高いバリエーションが勝者です。

この例では:

* `1199120` の `improvementRate` は **26.57** です。
* `1199121` の `improvementRate` は **-15.5** です。

したがって、勝者のバリエーションは `1199120` です。

## JS と CSS コードを取得する

実験レベルのコードは、最初の実験レスポンスの以下のフィールドで確認できます:

* `commonJavaScriptCode`
* `commonCssCode`
* `globalScript`（カスタム実験スクリプト）

バリエーションレベルのコードを取得するには、Get a variation エンドポイントを使用します。

### リクエスト例

```bash theme={null}
curl -L "https://api.kameleoon.com/variations/1199120" \
-H "Accept: */*" \
-H "Authorization: Bearer <ACCESS_TOKEN>"
```

### レスポンス例

```json theme={null}
{
  "id": 804410,
  "siteId": 24101,
  "name": "Variation 1",
  "jsCode": "(function() {})();",
  "cssCode": "/* Add CSS code to this variation */",
  "isJsCodeAfterDomReady": false
}
```

### コードの場所

バリエーションレベルのコードは、以下のフィールドで確認できます:

* **JavaScript コード**: `jsCode`
* **CSS コード**: `cssCode`

## 完全な Python スクリプト

次のスクリプトは、フィルタの構築、実験の取得、勝者バリエーションの特定、コードの抽出までのワークフロー全体を自動化します。

```python theme={null}
import requests
import json
import urllib.parse
import time
from datetime import datetime

# ==============================
# Configuration
# ==============================

ACCESS_TOKEN = "<ACCESS TOKEN>"
BASE_URL = "https://api.kameleoon.com"
DATE_FILTER = "2026-01-01T00:00:00"

HEADERS = {
    "Accept": "*/*",
    "Authorization": f"Bearer {ACCESS_TOKEN}"
}


# ==============================
# Step 1: Build and Encode Filter
# ==============================

def build_filter():
    filter_payload = [
        {
            "field": "status",
            "operator": "IN",
            "parameters": ["PAUSED", "STOPPED"]
        },
        {
            "field": "dateStatusModified",
            "operator": "GREATER",
            "parameters": [DATE_FILTER]
        },
        {
            "field": "type",
            "operator": "IN",
            "parameters": ["DEVELOPER"]
        }
    ]

    filter_json = json.dumps(filter_payload)
    encoded_filter = urllib.parse.quote(filter_json)
    return encoded_filter


# ==============================
# Step 2: Retrieve Experiments
# ==============================

def get_filtered_experiments(encoded_filter):
    url = f"{BASE_URL}/experiments?filter={encoded_filter}"
    response = requests.get(url, headers=HEADERS)
    response.raise_for_status()
    return response.json()


# ==============================
# Step 3: Retrieve Experiment Results
# ==============================

def get_experiment_results(experiment_id, main_goal_id):
    url = f"{BASE_URL}/experiments/{experiment_id}/results"

    payload = {
        "visitorData": False,
        "sequentialTesting": True,
        "referenceVariationId": "0",
        "goalsIds": [main_goal_id]
    }

    response = requests.post(url, headers={
        **HEADERS,
        "Content-Type": "application/json"
    }, json=payload)

    response.raise_for_status()
    data_code = response.json()["dataCode"]

    experiment_results = requests.get(f"{BASE_URL}/results?dataCode={data_code}")

    if experiment_results.json().get("status") != "READY":
        print("Results not ready. Waiting 1s and retrying.")
        time.sleep(1)
        experiment_results = requests.get(f"{BASE_URL}/results?dataCode={data_code}")

    return experiment_results.json()


# ==============================
# Step 4: Identify Winning Variation
# ==============================

def get_winning_variation(results_json, main_goal_id):
    variation_data = results_json.get("data", {}).get("variationData", {})

    best_variation_id = None
    best_improvement = float("-inf")

    for variation_id, variation_content in variation_data.items():

        # Skip reference
        if variation_id == "_reference":
            continue

        try:
            goal_data = (
                variation_content["breakdownData"]["_reference"]
                ["generalData"]["goalsData"][str(main_goal_id)]
            )

            improvement = goal_data.get("improvementRate", None)

            if improvement is not None and improvement > best_improvement:
                best_improvement = improvement
                best_variation_id = variation_id

        except KeyError:
            continue

    return best_variation_id, best_improvement


# ==============================
# Step 5: Retrieve Variation Code
# ==============================

def get_variation_code(variation_id):
    url = f"{BASE_URL}/variations/{variation_id}"
    response = requests.get(url, headers=HEADERS)
    response.raise_for_status()
    return response.json()


# ==============================
# Main Workflow
# ==============================

def main():
    print("Building filter...")
    encoded_filter = build_filter()

    print("Retrieving experiments...")
    experiments = get_filtered_experiments(encoded_filter)

    if not experiments:
        print("No experiments found.")
        return

    for experiment in experiments:
        experiment_id = experiment["id"]
        main_goal_id = experiment.get("mainGoalId")

        print(f"\nProcessing experiment {experiment_id}...")

        if not main_goal_id:
            print("No main goal defined. Skipping.")
            continue

        print("Retrieving results...")
        results = get_experiment_results(experiment_id, main_goal_id)

        if results.get("status") != "READY":
            print("Results not ready. Skipping.")
            continue

        winning_variation_id, improvement = get_winning_variation(results, main_goal_id)

        if not winning_variation_id:
            print("No winning variation found.")
            continue

        print(f"Winning variation: {winning_variation_id} (Improvement: {improvement}%)")

        print("Retrieving JS and CSS code...")
        variation_data = get_variation_code(winning_variation_id)

        global_js_code = experiment.get("globalScript","")
        common_css_code = experiment.get("commonCssCode","")
        common_js_code = experiment.get("commonJavaScriptCode","")
        js_code = variation_data.get("jsCode", "")
        css_code = variation_data.get("cssCode", "")
        
        print("\n--- Global JavaScript Code ---")
        print(global_js_code)

        print("\n--- Common JavaScript Code ---")
        print(common_js_code)

        print("\n--- Common CSS Code ---")
        print(common_css_code)

        print("\n--- JavaScript Code ---")
        print(js_code)

        print("\n--- CSS Code ---")
        print(css_code)


if __name__ == "__main__":
    main()
```
