AWS Lambda function - can't call update thing shadow

Viewed 3933

According to boto3 documentation here: https://boto3.readthedocs.org/en/latest/reference/services/iot-data.html#client the update_thing_shadow method takes the thingName & JSON payload as parameters. Currently it reads:

    client = boto3.client('iot-data', region_name='us-east-1')
    data = {"state" : { "desired" : { "switch" : "on" }}}
    mypayload = json.dumps(data)
    response = client.update_thing_shadow(
        thingName = 'MyDevice', 
        payload = b'mypayload'
    )

When I use the command line there's no problem but can't seem to get it right from within the lamba function. I've called it with numerous versions of code (json.JSONEncoder, bytearray(), etc..) without any luck. The errors range from syntax to (ForbiddenException) when calling the UpdateThingShadow operation: Bad Request: ClientError. Has anyone had success calling this or a similar method from within a AWS lambda function? Thanks.

2 Answers

This code is working fine for me:

def set_thing_state(thingName, state):
    # Change topic, qos and payload
    payload = json.dumps({'state': { 'desired': { 'property': state } }})

    logger.info("IOT update, thingName:"+thingName+", payload:"+payload)
    #payload = {'state': { 'desired': { 'property': state } }}


    response = client.update_thing_shadow(
        thingName = thingName, 
        payload =  payload
        )

    logger.info("IOT response: " + str(response))  
    logger.info("Body:"+response['payload'].read())


def get_thing_state(thingName):

    response = client.get_thing_shadow(thingName=thingName)

    streamingBody = response["payload"]
    jsonState = json.loads(streamingBody.read())

    print jsonState
    #print jsonState["state"]["reported"]

Good luck

Related