rubyamazon-web-servicesaws-lambdaaws-sdk-ruby

Getting the event body attributes in Ruby with AWS Lambda


So I'm new to ruby and I have a simple REST API.

The post request looks like this:

POST /endpoint, { 'message': 1 }

My lambda handler looks like this:

def run(event:, context:)
    puts "#{event['body']}"
    # prints the request body
end

I'm trying to figure out how to store message, which is an int in a variable.

I was trying to do something like this but doesn't work

my_int = event['body']['message']

Solution

  • event['body'] is going to return a string, a json string.

    You need to parse it with something like this.

    body = JSON.parse(event['body'])
    my_int = body['message']
    

    Also if you were to do.

    puts event.inspect
    

    instead of

    puts "#{event['body']}"
    

    you would have been able to see that body returned a string and not an object. I hope that helps and good luck.