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

# 複数のアカウントを削除する

> レート制限を効果的に管理しながら、Automation API を使用して複数のアカウントを削除する方法を学びます。

このガイドでは、[API のレート制限](/developer-docs/apis/automation-api-rest/get-started/get-started#rate-limiting) を順守しながら、Automation API を使用して複数のアカウントを削除する方法を説明します。[Delete account](/api-reference/account/delete-an-account) エンドポイントを使用します。

## 前提条件

<Info>
  Automation API を使用する前に、アクセストークンを取得する必要があります。手順については [認証ガイド](/developer-docs/apis/automation-api-rest/get-started/get-started#1-obtain-an-access-token) を参照してください。
</Info>

すべてのリクエストの `Authorization` ヘッダーにトークンを含めます:

```http theme={null}
Authorization: Bearer YOUR_ACCESS_TOKEN
```

## レート制限への対処

Automation API は、リクエストトラフィックを制御するために 2 つのレート制限ウィンドウを適用します:

| 時間枠  | 最大リクエスト数    |
| :--- | :---------- |
| 10 秒 | 50 リクエスト    |
| 1 時間 | 1,000 リクエスト |

<Warning>
  リクエストを早く送信しすぎると、API は `HTTP 429 Too Many Requests` ステータスコードを返します。
</Warning>

これらの制限を回避するには、リクエストを制御されたバッチで処理します:

* 10 秒ごとに最大 50 リクエストを送信します。
* 1 時間あたり最大 1,000 リクエストを送信します。

### 例: 230 個のアカウントを削除する

230 個のアカウントを削除するには、リクエストを以下のバッチに分割します:

| バッチ | リクエスト数 | 待機時間   |
| :-- | :----- | :----- |
| 1   | 50     | 10 秒待機 |
| 2   | 50     | 10 秒待機 |
| 3   | 50     | 10 秒待機 |
| 4   | 50     | 10 秒待機 |
| 5   | 30     | 完了     |

## Python を使用してアカウントを削除する

次の Python スクリプトを使用して、削除リクエストを順次送信し、レート制限を自動的に管理します:

```python delete_accounts.py theme={null}
import time
import requests

API_URL = "https://api.kameleoon.com/accounts/"
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"

ACCOUNT_IDS = [12345, 54321]

MAX_PER_10_SECONDS = 50
MAX_PER_HOUR = 1000

TEN_SECONDS = 10
ONE_HOUR = 3600


def delete_account(session, account_id):
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
    }

    url = f"{API_URL}{account_id}"

    try:
        response = session.delete(url, headers=headers)

        if response.status_code == 429:
            return "rate_limited", None

        if response.status_code in (200, 204):
            return True, response.json() if response.content else {}

        return False, response.text

    except requests.exceptions.RequestException as e:
        return False, str(e)


def process_accounts(account_ids):

    session = requests.Session()

    start_hour = time.monotonic()
    hour_count = 0

    for i in range(0, len(account_ids), MAX_PER_10_SECONDS):

        batch = account_ids[i:i + MAX_PER_10_SECONDS]

        # Enforce hourly limit BEFORE sending requests
        if hour_count + len(batch) > MAX_PER_HOUR:
            elapsed = time.monotonic() - start_hour
            sleep_time = max(0, ONE_HOUR - elapsed)

            print(f"Hourly limit reached. Sleeping {sleep_time:.2f} seconds")
            time.sleep(sleep_time)

            start_hour = time.monotonic()
            hour_count = 0

        batch_start = time.monotonic()

        for account_id in batch:

            while True:
                # Check hourly limit before EACH request
                if hour_count >= MAX_PER_HOUR:
                    elapsed = time.monotonic() - start_hour
                    sleep_time = max(0, ONE_HOUR - elapsed)

                    print(f"Hourly limit reached. Sleeping {sleep_time:.2f} seconds")
                    time.sleep(sleep_time)

                    start_hour = time.monotonic()
                    hour_count = 0

                result, data = delete_account(session, account_id)

                # Count every attempt as a request
                hour_count += 1

                if result == True:
                    print(f"Account {account_id} deleted")
                    break

                elif result == "rate_limited":
                    elapsed = time.monotonic() - start_hour

                    # If close to hourly limit, wait for full reset
                    if hour_count >= MAX_PER_HOUR or elapsed >= ONE_HOUR:
                        sleep_time = max(0, ONE_HOUR - elapsed)
                        print(f"429 likely due to hourly limit. Sleeping {sleep_time:.2f} seconds")
                        time.sleep(sleep_time)

                        start_hour = time.monotonic()
                        hour_count = 0
                    else:
                        print("429 received. Waiting 10 seconds...")
                        time.sleep(TEN_SECONDS)

                    continue

                else:
                    print(f"Failed to delete {account_id}: {data}")
                    break

        # Enforce 10-second window
        elapsed = time.monotonic() - batch_start

        if elapsed < TEN_SECONDS:
            sleep_time = TEN_SECONDS - elapsed
            print(f"Waiting {sleep_time:.2f} seconds before next batch")
            time.sleep(sleep_time)


def main():
    process_accounts(ACCOUNT_IDS)


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

このスクリプトは、以下を行うことで、Automation API のレート制限を順守しつつアカウント削除を管理します:

* リクエストを順次送信する。
* アカウントを 50 のバッチで処理する。
* 10 秒の制限を強制するためにバッチ間で待機する。
* プロセスが 1 時間あたり 1,000 リクエストの制限に達した場合は一時停止する。

このアプローチにより、レート制限エラーを防ぎ、大規模なクリーンアップやオフボーディング作業中の信頼性の高いアカウント削除を保証します。
