Note: This article was first published more than a year ago.

  • SwitchBot API endpoints, token methods, rate limits, and app screens change frequently. Refer to the latest developer documentation.
  • These Python examples assume the libraries available at the time. Check dependency maintenance and the recommended implementation.
  • Available state values may differ with the combination of device firmware and app version.

This guide uses the latest SwitchBot API available in May 2024 from Python. It all starts with retrieving the device list through API v1.1. The API requires an Open Token, which you generate through the app. Install the SwitchBot app from the App Store or Google Play Store, then register an account or log in. Generate the Open Token as follows:

  1. Go to Profile > Settings.
  2. Tap the app version ten times to reveal Developer Options.
  3. Open Developer Options.
  4. Retrieve the token.

This provides the Open Token and client secret, also called the secret key.

Product listings for devices to use with the API: Search Amazon for SwitchBot products (Ad)

SwitchBot API v1.1

https://github.com/OpenWonderLabs/SwitchBotAPI

SwitchBot API v1.1 requires a unique signature generated from the token and client secret to access private data.

The authentication token and signature are checked together when a request is made.

Generate a 13-digit timestamp and concatenate it with the token.

Generate the signature using the secret key and the string from the previous step.

Convert the signature to uppercase.

You need Python 3.6 or later, requests, and pandas. Prepare Python and a virtual environment as appropriate. Here is an example of installing requests and pandas.

pip install requests pandas

Here is the sample code. It retrieves the device list through the SwitchBot API, converts the result to a DataFrame, and displays it. Put your Open Token in api_token and your client secret in secret_token. Replace the XXXXXXX placeholders with your keys, leaving the surrounding punctuation in place. switchbot_device_api_client.py

import requests
import time
import uuid
import hmac
import hashlib
import base64
import pandas as pd

def get_device_list(api_token, secret_token):
    url = "https://api.switch-bot.com/v1.1/devices"
    t = int(time.time() * 1000)
    nonce = str(uuid.uuid4())
    string_to_sign = f"{api_token}{t}{nonce}".encode('utf-8')
    secret_key = secret_token.encode('utf-8')
    signature = hmac.new(secret_key, string_to_sign, hashlib.sha256).digest()
    sign = base64.b64encode(signature).decode('utf-8').upper()

    headers = {
        "Authorization": api_token,
        "Content-Type": "application/json",
        "t": str(t),
        "nonce": nonce,
        "sign": sign
    }

    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return response.json()
    else:
        return response.status_code, response.text

api_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
secret_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
devices = get_device_list(api_token, secret_token)

print(devices)

if isinstance(devices, dict) and 'body' in devices and 'deviceList' in devices['body']:
    data = devices['body']['deviceList']
    df = pd.DataFrame(data, columns=['deviceId', 'deviceName', 'deviceType', 'enableCloudService', 'hubDeviceId'])
    print(df.to_string(index=False))
else:
    print("Failed to retrieve the device list.")

Some notes on the code:

import requests # HTTPリクエストを送信するためのライブラリ
import time # 時間関連の関数を提供するモジュール
import uuid # UUID(一意識別子)を生成するためのモジュール
import hmac # HMAC(ハッシュベースのメッセージ認証コード)を生成するためのモジュール
import hashlib # ハッシュ関数を提供するモジュール
import base64 # Base64エンコード/デコードを行うためのモジュール
import pandas as pd # データ操作と分析のためのライブラリ

That is the relevant part.

The get_device_list(api_token, secret_token) function communicates with the SwitchBot API.

It first specifies the URL of the API endpoint used to retrieve SwitchBot device information for an authenticated request.

It then obtains the current time in milliseconds for the request timestamp and generates a random UUID nonce to improve security.

These are combined with the API token into a signing string, which is signed with HMAC-SHA256 using the secret token.

Finally, the signature is Base64-encoded, converted to uppercase, and used in the request headers.

Next, the code prepares an HTTP GET request to the SwitchBot API.

First, it sets the required headers.

These include the API token, JSON content type, timestamp, unique nonce, and signature.

Setting these header values provides authentication and data-integrity verification.

The script sends a GET request to the API URL with those headers.

If the request succeeds with status code 200, the API returns JSON data.

If it fails, the script returns the status code and an error message.

Running it displays deviceId, deviceName, deviceType, enableCloudService, and hubDeviceId.

The deviceId can then be used with the SwitchBot API to control each device directly, including on/off commands and changes to settings.

You could also create automation rules and integrate it with other systems.

Using Python for these operations makes it possible to build an efficient, flexible smart-home setup.

The limit described here is 10,000 API requests per day; exceeding it produces an authentication error. Some devices require Cloud Services to be enabled, and some can only be operated through a hub.

SwitchBot API v1.1

https://github.com/OpenWonderLabs/SwitchBotAPI