How do you set states using HTTP API with Python?

Hi, I am trying to set states using the HTTP API in Python. My current code is thus

import requests

token = "xxx"

headers = {
    "Authorization": "Bearer %s" % token,
}

payload = {
  "states": [
    {
        "selector" : "all",
        "hue": 200,
        "brightness": 0.1
    },
    {
         "selector" : "all",
         "brightness": 0.5
    },
    {
         "selector" : "all",
      "brightness": 0.1
    },
    {
         "selector" : "all",
         "power": "off"
    }
  ],
  "defaults": {
    "power": "on",
    "saturation": 0,
    "duration": 2.0

}

}

response = requests.put(‘https://api.lifx.com/v1/lights/states’, data=payload, headers=headers)
print(response.content)

However I keep getting a 500 error: b’{“error”:“Error occured while processing request. Error ID: 08a49b347fcb5fc4f58af86f3c246b3370b6de2a98493a10707263c4db945477”}’

I am really struggling to get the set states and cycle commands to work. Can anyone help out please?

You are selecting all the lights over and over again. Try selecting individual lights.

Most of the python examples on the api page depend on the fact that our API supports receiving data as either HTTP POST style parameters or JSON parameters. The states and the cycle endpoint are the exceptions to this because they both accept complex data structures. Unfortunately the way that the python requests library processes the data is not compatible with how our API expects to read it. The best way to work around this is to instead send it as JSON. It’s a pretty simple change to make, just import the json module then call json.dumps() on the payload before you send it, so the example you linked above becomes:

import requests
import json

token = "xxx"

headers = {
    "Authorization": "Bearer %s" % token,
}

payload = {
  "states": [
    {
        "selector" : "all",
        "hue": 200,
        "brightness": 0.1
    },
    {
         "selector" : "all",
         "brightness": 0.5
    },
    {
         "selector" : "all",
      "brightness": 0.1
    },
    {
         "selector" : "all",
         "power": "off"
    }
  ],
  "defaults": {
    "power": "on",
    "saturation": 0,
    "duration": 2.0

}

}

response = requests.put('https://api.lifx.com/v1/lights/states', data=json.dumps(payload), headers=headers)
print(response.content)
1 Like