Lambda and API Gateway

13 January, 2021
Back

AWS Tutorial.

In this tutorial, a Lambda function returns a string with a name passed to it via a GET request. I simplified the code so there would be less params. You'd also need to complete the tutorial before this makes sense.

Lambda functions don't have their own URLs. Therefore, you need to attach an API Gateway to get an endpoint like so: https://k3g2fcsc3e.execute-api.ap-southeast-1.amazonaws.com/test/test.

And when you want to send a GET request, it'll look like this: https://k3g2fcsc3e.execute-api.ap-southeast-1.amazonaws.com/test/test?name=Richard. The parameter passed was "name":"Richard".

After calling this endpoint, you need a way for Lambda to retrieve the value. Lambda can access it with this code:

name = event.queryStringParameters.name

This is the full Lambda code in the index.js file:

console.log('Loading function');

exports.handler = async (event) => {

console.log("request: " + JSON.stringify(event))

name = event.queryStringParameters.name

let responseBody = {
    message: `My name is ${name}`,
    input: event
}

let response = {
    statusCode: 200,
    headers: {
        "x-custom-header" : "This is a header"
    },
    body: JSON.stringify(responseBody)
}

console.log("response: " + JSON.stringify(response))
return response
};

What you see in the browser would be a mess of words in this structure:

{
  "message": "My name is Richard",
  "input": {
    bla
    bla
    bla
  }
}

It's just returning to you the event. But if you'd like to see something neater, change the code in line 11 from "input":"event" to "input":"name". And hopefully it becomes clearer.


Back