Part 4: Integrate Lambda with API Gateway

So far we have seen the introduction of different AWS tutorial used in this tutorial, created a static website and created a lambda function. Now is the time to integrate our lambda function and UI to API Gateway.

Create API Gateway

  1. Go back to AWS console home page and click on API Gateway service.
  2. Click on Get Started in the API Gateway home page.
  3. Select New API radio button. In the given form fill out the API name and Endpoint Type. If you want your API to be available only for a particular region then choose Regional or else Edge Optimized. Click Save.
  4. Now API is created. Click on API and click on Resources menu item.
  5. In the Actions dropdown, click Create Resource. Fill in the required details as shown in the image below. Also select the Enable API Gateway CORS., since we will call this from a different origin.

    API Gateway png
    Create Resource
  6. Now click on the created resource, send-mail in our case, and from Actions dropdown select Create Method. It will ask for method type, select POST and click on tick mark to create POST method.
  7. Now fill out all the required details. Select the appropriate region for Lambda Region and the correct name for Lambda Function. In my case, I have created the Lambda function in ap-south-1 (Mumbai) region and the function that we have created is static-website-send-email. Click Save. Click OK for permissions popup.

    Create API Method png
    Create Method
  8. We have created the API but haven’t deployed it. So lets deploy it.
  9. From Actions dropdown, select Deploy API.
  10. In the popup, select any of your deployment stages or create a new one and select it. Then click on Deploy. Deployment completed.
  11. You can see the Invoke URL in the next screen. If you are unable to find the Invoke URL, then go back to API home page, click on the new API and select Stages. Now click on the deployment stage that you have deployed the API, now you can see the Invoke URL. Note it down for integration.

API Gateway Error Handling

  1. Since our code in lambda function has two error types. One with status 401 and another one with status 500, we should cater for those in the API method response.
  2. Go back to the POST method and click on the Method Response.
  3. Click Add Response and add 500 as one error code. Similarly add another response for 400.
  4. Go back to the POST method and click on the Integration Response.
  5. Click Add Integration Response and add the following error. Text in Regex box is .*DataImproper.*

    Data Improper png
    Date Improper Response
  6. Click Add Integration Response and add the following error. Text in Regex box is .*InternalError.*

    Internal Error png
    Internal Error Response
  7. Deploy the API again following the previous instructions. Invoke URL should still remain the same.

Integrate API Gateway to UI

  1. Since we want to invoke this API method from contact page, go to contact.html and add the following jQuery 1.12.4 CDN library in the <head> section.
    <script src="http://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
  2. Add the following script tag as the last line in <body> tag
    <script src="scripts/contact.js"></script>
  3. In contact.html change input type submit to input type button (for class send).
  4. Now create folder called scripts in the root directory of the website template folder. In this scripts folder add contact.js file with the following content. Important: Replace api-url in https://api-url/send-email with your Invoke URL. 
    function validateEmail(email) {
       var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
       return re.test(email);
    }
    
    (function($) {
       $(".send").on("click", function (ev) {
          var body = $("#message").val();
          var from= $("#name").val();
          var fromEmail = $("#emailadd").val();
          var error =false;
          if (!body || body.trim() =="") {
             error = true;
          }
    
          if (!from||from.trim() =="") {
             error = true;
          }
    
          if (!fromEmail || fromEmail.trim() =="") {
             error = true;
          } else if (!validateEmail(fromEmail)) {
             error = true;
          }
    
          if (error) {
             alert("Please fill all fields and check if e-mail is in proper format.");
             return;
          }
    
          $.ajax("https://2gbt5co6ob.execute-api.ap-south-1.amazonaws.com/Prod/send-email", {
             method: "POST",
             data: JSON.stringify({
                body: body,
                from: from,
                fromEmail: fromEmail
             }),
             beforeSend: function (x) {
                x.setRequestHeader("Content-Type", "application/json")
             }
          }).done(function () {
             $("#message").val("");
             $("#name").val("");
             $("#emailadd").val("");
             alert("An email has been sent to us. We will respond to you at the earliest possible time.");
          }).fail(function () {
             alert("Oops! There is something wrong.");
          });
       });
    })(jQuery);
  5. Now upload your contact.html and contact.js to the respective folders in the S3 bucket.
  6. Finally our website got a new functionality to send an email.

Important: If there is an error in AJAX call with statusCode==0, then it is most probably due to CORS in API method. So you should go to the API method (send-email in our case) and Enable CORS again using Actions dropdown. Don’t forget to re-deploy after enabling CORS.

So our tutorial is complete. Hope you enjoyed it. Please provide your feedback. 🙂

Previous: Lambda function for AWS SES using API Gateway

 

Please follow and like us:
error

Leave a Reply

Your email address will not be published. Required fields are marked *