I am using AWS Lambda
with python-2.7
replying back to AWS Api Gateway
. My lambda function should return a response looking like following, but I am strugling with putting the proper form of body in the JSON response:
return_value = {
"statusCode": 200,
"isBase64Encoded": 'false',
"headers": {"Content-Type": "application/json"},
"body": {payload['note']}
}
the type of payload['note']
is unicode
, so I don't know what exactly to put in the brackets opposite to body
, as I am new to python and tried a lot without being able to figure it out. I tried to convert it to string using:
unicodedata.normalize('NFKD', payload['note']).encode('ascii', 'ignore')
But it didn't work either.
First, I believe it is a good idea to convert the unicode string to a python string before, since I dont know if the rest of your code can handles unicode in json.
I think your problem is related to json formatting. As JSON, the body field should contain key-value pairs.
Try with :
return_value = {
"statusCode": 200,
"isBase64Encoded": 'false',
"headers": {"Content-Type": "application/json"},
"body": {"note": payload['note']}
}
It's probably best to build it using standard objects first, then convert it to JSON as you return it. For example:
# coding=utf-8
import json
def aws_message(payload):
message = dict(statusCode=200,
isBase64Encoded=False,
headers={"Content-Type": "application/json"},
body=payload['note'])
return json.dumps(message)
if __name__=="__main__":
payload = dict(note='something')
print(aws_message(payload))
Unfortunately you'll notice I switched from the long-form dict() creation to the short-hand when building the headers inside the message (it was a quick 'n dirty example). Here is the output:
C:\Python37\python.exe C:/dev/scratches/scratch_17.py
{"statusCode": 200, "isBase64Encoded": false, "headers": {"Content-Type": "application/json"}, "body": "something"}
As you can see, it's quite straight-forward to build the object in a fashion that is easy to understand, and then let the json library do all the conversion into a correctly-formatted response. I hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.