Skip to main content

Getting Started with the SwitchBot API v1.1

·548 words·3 mins

Introduction
#

SwitchBot is a popular smart home platform that lets you control lights, curtains, air conditioners, and more. What many people don’t know is that SwitchBot provides an open API that you can use to control your devices programmatically.

In this post, I’ll walk you through setting up the SwitchBot API v1.1 with Python.

Prerequisites
#

  • A SwitchBot account with at least one device
  • Python 3.8+
  • requests and python-dotenv packages
pip install requests python-dotenv

Step 1: Get Your API Credentials
#

  1. Open the SwitchBot app on your phone
  2. Go to ProfilePreferences
  3. Tap App Version 10 times to enable Developer Options
  4. Go to Developer Options
  5. Copy your Token and Secret Key

Step 2: Store Credentials Securely
#

Create a .env file in your project directory:

SWITCHBOT_TOKEN=your_token_here
SWITCHBOT_SECRET=your_secret_here

Important: Never commit this file to git! Add .env to your .gitignore.

Step 3: Authentication
#

The SwitchBot API v1.1 uses HMAC-SHA256 for authentication. Every request needs signed headers with a token, timestamp, nonce, and signature.

Here’s the authentication function:

import hashlib
import hmac
import base64
import time
import uuid
import os
import requests
from dotenv import load_dotenv

load_dotenv()

API_BASE = "https://api.switch-bot.com/v1.1"
TOKEN = os.getenv("SWITCHBOT_TOKEN", "")
SECRET = os.getenv("SWITCHBOT_SECRET", "")

def generate_headers(token: str, secret: str) -> dict:
    """Generate authentication headers for SwitchBot API v1.1."""
    nonce = str(uuid.uuid4())
    t = str(int(time.time() * 1000))
    string_to_sign = f"{token}{t}{nonce}"
    sign = base64.b64encode(
        hmac.new(
            secret.encode("utf-8"),
            string_to_sign.encode("utf-8"),
            hashlib.sha256,
        ).digest()
    ).decode("utf-8")

    return {
        "Authorization": token,
        "sign": sign,
        "nonce": nonce,
        "t": t,
        "Content-Type": "application/json; charset=utf8",
    }

How it works:
#

  1. Generate a random nonce (UUID) and timestamp (milliseconds)
  2. Create a string: token + timestamp + nonce
  3. Sign it with HMAC-SHA256 using your secret key
  4. Base64-encode the signature
  5. Send all values in the request headers

Step 4: List Your Devices
#

def get_devices(token: str, secret: str) -> dict:
    """Get all SwitchBot devices."""
    headers = generate_headers(token, secret)
    response = requests.get(f"{API_BASE}/devices", headers=headers)
    response.raise_for_status()
    return response.json()

# List all devices
result = get_devices(TOKEN, SECRET)
for device in result["body"]["deviceList"]:
    print(f"{device['deviceName']} ({device['deviceType']}) - {device['deviceId']}")

This will output something like:

Living Room Light (Color Bulb) - ABCDEF123456
Bedroom Curtain (Curtain3) - 123456ABCDEF

Step 5: Get Device Status
#

def get_device_status(token: str, secret: str, device_id: str) -> dict:
    """Get status of a specific device."""
    headers = generate_headers(token, secret)
    response = requests.get(
        f"{API_BASE}/devices/{device_id}/status", headers=headers
    )
    response.raise_for_status()
    return response.json()

status = get_device_status(TOKEN, SECRET, "YOUR_DEVICE_ID")
print(status)

Step 6: Send Commands
#

def send_device_command(token: str, secret: str, device_id: str,
                        command: str, parameter: str = "default",
                        command_type: str = "command") -> dict:
    """Send a command to a device."""
    headers = generate_headers(token, secret)
    payload = {
        "command": command,
        "parameter": parameter,
        "commandType": command_type,
    }
    response = requests.post(
        f"{API_BASE}/devices/{device_id}/commands",
        headers=headers,
        json=payload,
    )
    response.raise_for_status()
    return response.json()

# Turn on a light
send_device_command(TOKEN, SECRET, "DEVICE_ID", "turnOn")

# Set brightness to 50%
send_device_command(TOKEN, SECRET, "DEVICE_ID", "setBrightness", "50")

# Set color (RGB)
send_device_command(TOKEN, SECRET, "DEVICE_ID", "setColor", "255:100:0")

Common Device Commands
#

Device TypeCommandParameter
Color BulbturnOn / turnOffdefault
Color BulbsetBrightness1-100
Color BulbsetColorR:G:B (0-255)
CurtainturnOn (open) / turnOff (close)default
CurtainsetPosition0-100
BotturnOn / turnOff / pressdefault

What’s Next
#

In the next post, I’ll cover:

  • Setting up webhooks to receive real-time device updates
  • Building a GUI controller with Tkinter
  • Creating scenes and automations via the API

The full source code is available on GitHub.

Happy automating!