Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda python API call method not returning JSON - not serialisable?

I have a Lambda function, which is a basic Python GET call to an API. It works fine locally, however when I upload to Lambda (along with the requests library) it will not return the JSON response from the API call. I simply want it to return the entire JSON object to the caller. Am I doing something fundamentally wrong here - I stumbled across a couple of articles saying that returning JSON from a Lambda Python function is not supported.

Here is the code:

import requests
import json
url = "http://url/api/projects/"
headers = {
   'content-type': "application/json",
   'x-octopus-apikey': "redacted",
   'cache-control': "no-cache"
    }

def lambda_handler(event, context):
    response = requests.request("GET", url, headers=headers)
    return response

My package contains the requests library and dist, and the json library (I don't think it needs this though). Error message returned is:

    {
  "stackTrace": [
    [
      "/usr/lib64/python2.7/json/__init__.py",
      251,
      "dumps",
      "sort_keys=sort_keys, **kw).encode(obj)"
    ],
    [
      "/usr/lib64/python2.7/json/encoder.py",
      207,
      "encode",
      "chunks = self.iterencode(o, _one_shot=True)"
    ],
    [
      "/usr/lib64/python2.7/json/encoder.py",
      270,
      "iterencode",
      "return _iterencode(o, 0)"
    ],
    [
      "/var/runtime/awslambda/bootstrap.py",
      41,
      "decimal_serializer",
      "raise TypeError(repr(o) + \" is not JSON serializable\")"
    ]
  ],
  "errorType": "TypeError",
  "errorMessage": "<Response [200]> is not JSON serializable"
}
like image 238
kafka Avatar asked Jan 20 '17 12:01

kafka


People also ask

How do I return AWS Lambda value?

Returning a valueIf you use the RequestResponse invocation type, such as Synchronous invocation, AWS Lambda returns the result of the Python function call to the client invoking the Lambda function (in the HTTP response to the invocation request, serialized into JSON).


1 Answers

I've resolved this - the problem with my Python code is that it was trying to return the entire response, rather than simply the JSON body (the code for my local version prints 'response.text'). In addition, I have ensured that the response is JSON formatted (rather than raw text). Updated code:

import requests
import json
url = "http://url/api/projects/"
headers = {
   'content-type': "application/json",
   'x-octopus-apikey': "redacted",
   'cache-control': "no-cache"
    }

def lambda_handler(event, context):
    response = requests.request("GET", url, headers=headers)           
    try:
        output = response.json()
    except ValueError:
        output = response.text
    return output
like image 54
kafka Avatar answered Sep 21 '22 22:09

kafka