Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serverless Framework Python lambda return JSON directly

I'm trying to find out how can I return the response as a JSON directly using Serverless Framework. This is a function on AWS with Lambda Proxy Integration. All default setting. The goal is to from the python lambda function, the HTTP response client gets is directly a JSON object, instead of a string serialization of a JSON.

The python handler is as simple as this one

    def handle(event, context):
        log.info("Hello Wold")
        log.info(json.dumps(event, indent=2))
        return {
            "statusCode": 200,
            "body": {"foo": "bar"},
            "headers": {
                "Content-Type": "application/json"
            }
        }

The function looks like this:

    functions:
      report:
        handler: handler.handle
        events:
          - http:
              path: api/mypath
              method: post
              authorizer: aws_iam

With these configurations, the response BODY I get in Postman is:

    {
        "statusCode": 200,
        "body": {
            "foo": "bar"
        },
        "headers": {
            "Content-Type": "application/json"
        }
    }

So this is strange, why I get everything as body? How do I configure it properly so that I only get the "real" body?

like image 426
pythonician_plus_plus Avatar asked Jan 26 '23 14:01

pythonician_plus_plus


2 Answers

approach #1

Use json.dumps() to convert JSON to string.

import json
def handle(event, context):
    log.info("Hello Wold")
    log.info(json.dumps(event, indent=2))
    return {
        "statusCode": 200,
        "body": json.dumps({"foo": "bar"}),
        "headers": {
            "Content-Type": "application/json"
        }
    }

approach #2

Use lambda integration and avoid json.dumps(). But this will transform your output as

{ foo = bar}
like image 111
secretshardul Avatar answered Jan 31 '23 09:01

secretshardul


The body needs to be stringified when working with API Gateway

The pythonish way to do it is to pass the JSON body into the json.dumps function.

def handle(event, context):
  log.info("Hello Wold")
  log.info(json.dumps(event, indent=2))
  return {
      "statusCode": 200,
      "body": json.dumps({"foo": "bar"}),
      "headers": {
          "Content-Type": "application/json"
      }
  }
like image 37
Thales Minussi Avatar answered Jan 31 '23 11:01

Thales Minussi