Saturday, 28 October 2017

How to use Lambda function with API gateway

Background

We have seen some aspects of AWS before like using EC2, S3 , IAM. You can revisit those posts again with below filter -
In this post we will see some of the hot topics in AWS -
  1. Lambda functions(Compute) and 
  2. API gateways(Application services)
We have come a long way in terms of our code deployments. Below diagram shows it all -





 Big companies have their own data centers perhaps for security concerns. But if you think from a startup perspective it has become very simple now. All you need to worry about is your application code.After datacenters we had IaaS (Infrastructure as a service) where we had access to operating systems and we can use it as we see fit without worrying about the underlying hardware. For eg. using Virtual machines. Amazon EC2 is a good example if that. You spin up a Ubuntu and get to work. Next level of ease came with PaaS (Platform as a service) where you need not worry about the OS and just concentrate on your language runtime and application. Popular examples are Google app engine or IBM bluemix or Amazon Elastic Beanstalk. This is the age of serverless platforms where you don't even have to worry about language runtimes. You can concentrate in your business logic. This brings us to our topic of interest - Lambda functions.

In this post we will see how to create a lambda function. Put it behind a API gateway and access this API from a static website hosted from S3. So lets get started.


How to use Lambda function with API gateway

Let's start with a Lambda function. Go to Lambda service and create a new function. Let's call it MyTestFunction

Make changes so that your code looks like following -

exports.lambda_handler = (event, context, callback) => {
    // TODO implement
    callback(null, 'Hello from Lambda athakur!');
};


and change the Handler name to index.lambda_handler.

NOTE : Make sure string after index. in your handler name is same as the method name in the code.




 All we are doing here is when this Lambda function is invoked we are returning string - "Hello from Lambda athakur!"


Now before we add a trigger to Lambda to execute on API gateway call we need to first create an API from API gateway. So go to API gateway service and create an API.  Let's call it MyTestAPI.

You can create a resource if you want under this API. I am going to leave it as blank. Next go to Actions -> Create Method and create a GET request. It should look like below -




NOTE : Make sure your turn in CORS from Actions menu so that there are no issues while invoking this API from java script. CORS is Cross-origin resource sharing and turning it on allows invoking APIs from javascript with different domain/hostname than that from the site from which it is invoked. Since we are using S3 here it will have a different domain than this. So you need to turn it on.

Else you will get an error something like below -
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://test123.ap-south-1.amazonaws.com/dev. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).


 Once your API is ready you can test it using the test button on the screen.



 Once test is successful you can go to Action and deploy this API. You need to select a stage to deploy. If you don't have it already just create a new one called dev and deploy. Once you do that you should be able to go to stages section and see your endpoint i.e url to be invoked.




Note this URL down we will use it shortly from our javascript.

Now go back to triggers section of Lambda you created and select "API gateway" from the dropdown and link this API from there. Your screen should look like below -





 Our API and lambda is all setup. All we need to do now is call it from our static website. So now go to S3. Enable static website and give main file as index.html and upload index.html to the bucket with following content -

<html>
    <head>
<script>
    function callAwsLambdaFunction() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("myDiv").innerHTML = this.responseText;
            }
        };
        xhttp.open("GET", "https://qqzgu3j545.execute-api.ap-south-1.amazonaws.com/dev", true);
        xhttp.send();

    }
    </script>    
        <title>Hello World!</title>
    </head>
    <body>
        <h1>Hello world!</h1>
        <h1>Click below button to call API gatway and display result below!</h1>
        <h1><div id="myDiv"></div></h1>
        <button onclick="callAwsLambdaFunction()">Click me!</button><br>
        Regards,<br/>
        Aniket
    </body>
</html>


NOTE :  Make sure the index.html is publicly accessible . If not make it from permissions section.


Now open your index.html by opening it in a browser tab -




After you click on the "Click me" button it should make a call to API gateway and get result from our Lambda. This looks as follows -




Related Links

t> UA-39527780-1 back to top