Build a Basic Web Application

TUTORIAL

Module 2: Build a Serverless Function

In this module, you will build a serverless function using AWS Lambda

Overview

In this module, you will be writing a small piece of code, in Python, JavaScript, or Java, to be used in a later module to add interactivity to your web page. You will use AWS Lambda, a compute service that lets you create serverless functions, eliminating the need for you to manage software and hardware. Instead, applications are broken up into individual functions that can be invoked and scaled individually.

These serverless functions are triggered based on a specific event you will define in the code. It is also a very affordable service, because you are only charged for the number of events you process, not the idle time. Best of all, you do not have to worry about managing any servers.

What you will accomplish

In this module, you will:

  • Create a Lambda function from scratch using the AWS console (in Python, JavaScript, or Java)
  • Create (JSON) events in the AWS console to test your function

Key concepts

Compute service – A service that provides computational processing power.

Serverless function – Piece of code that will be executed by a compute service, on demand.

Lambda trigger – The type of event that will make a Lambda (serverless) function run. This can be another AWS service or an external input.

 Minimum time to complete

5 minutes

 Services used

 Last updated

April 4, 2023

Implementation

    • Python
      1. In a new browser tab, log in to the AWS Lambda console.
      2. Make sure you create your function in the same Region in which you created the web app in the previous module. You can see this at the very top of the page, next to your account name.
      3. Choose the orange Create function button.
      4. Under Function name, enter HelloWorldFunction.
      5. Select Python 3.8 from the runtime dropdown and leave the rest of the defaults unchanged.

      6. Choose the orange Create function button.

      7. You should see a green message box at the top of your screen with the following message "Successfully created the function HelloWorldFunction."

      8. Under Code source, replace the code in lambda_function.py with the following:

      # import the JSON utility package since we will be working with a JSON object
      import json
      # define the handler function that the Lambda service will use as an entry point
      def lambda_handler(event, context):
      # extract values from the event object we got from the Lambda service
          name = event['firstName'] +' '+ event['lastName']
      # return a properly formatted JSON object
          return {
          'statusCode': 200,
          'body': json.dumps('Hello from Lambda, ' + name)
          }

      9. Save by going to the file menu and selecting Save to save the changes.

      10. Choose Deploy to deploy the changes.

      11. Let's test our new function. Choose the orange Test button to create a test event by selecting Configure test event.

      12. Under Event name, enter HelloWorldTestEvent.

      13. Copy and paste the following JSON object to replace the default one:

      {
      "firstName": "Ada",
      "lastName": "Lovelace"
      }

      14. Choose the Save button at the bottom of the page.

    • JavaScript
      1. In a new browser tab, log in to the AWS Lambda console.
      2. Make sure you create your function in the same Region in which you created the web app in the previous module. You can see this at the very top of the page, next to your account name.
      3. Choose the orange Create function button.
      4. Under Function name, enter HelloWorldFunction.
      5. Select Node.js 16.x from the runtime drop-down and leave the rest of the defaults unchanged.

      6. Choose the orange Create function button.

      7. You should see a green message box at the top of your screen with the following message "Successfully created the function HelloWorldFunction."

      8. Under Code source, replace the code in index.js with the following:

      // Define handler function, the entry point to our code for the Lambda service
      // We receive the object that triggers the function as a parameter
      exports.handler = async (event) => {
          // Extract values from event and format as strings
          let name = JSON.stringify(`Hello from Lambda, ${event.firstName} ${event.lastName}`);
          // Create a JSON object with our response and store it in a constant
          const response = {
              statusCode: 200,
              body: name
          };
          // Return the response constant
          return response;
      };

      9. Choose the Deploy button located next to the orange Test button at the top of the code editor.

      10. Choose the orange Test button located at the top of the code editor.

      11. Under Event name, enter HelloWorldTestEvent.

      12. Copy and paste the following JSON object to replace the default one:

      {
      "firstName": "Ada",
      "lastName": "Lovelace"
      }

      13. Choose the Save button to create the test event.

      14. Choose the orange Test button again to run the test event. The result will be displayed in the Execution results section of the code editor.

    • Java
      1. In a new browser tab, log in to the AWS Lambda console.
      2. Make sure you create your function in the same Region in which you created the web app in the previous module. You can see this at the very top of the page, next to your account name.
      3. Choose the orange Create function button.
      4. Under Function name, enter HelloWorldFunction.
      5. Select Java 11 (Corretto) from the runtime dropdown and leave the rest of the defaults unchanged.

      6. Choose the orange Create function button.

      7. You should see a green message box at the top of your screen with the following message "Successfully created the function HelloWorldFunction."

      8. You have now created a Lambda function with a handler class named Hello. Since Java is a compiled language, you cannot view or edit the source code in the Lambda console, but you can modify its configuration, invoke it, and configure triggers.

      9. To update the function's code, you will need to create a deployment package, which is either a JAR file or a ZIP archive containing your function's code. For the purposes of this tutorial, we have provided a downloadable JAR file with the updated function code.

      10. Go to Function code and upload the JAR file.

      11. Update the Handler to com.example.app.LambdaRequestHandler::handleRequest.

      12. Choose the orange Save button at the top of your screen.

      13. Choose Select a test event at the top of the screen to test the new function.

      14. From that dropdown menu, select Configure test events.

      15. Under Event name, enter HelloWorldTestEvent.

      16. Copy and paste the following JSON object to replace the default one:

      {
      "firstName": "Ada",
      "lastName": "Lovelace"
      }

      17. Choose the orange Create button at the bottom of the page.

    1. Under the HelloWorldFunction section at the top of the page, select Test tab.
    2. You should see a light green box at the top of the page with the following text: Execution result: succeeded. You can choose Details to see the event the function returned.
    3. Well done! You now have a working Lambda function.

Application architecture

Now that we are done with this module, our architecture will look like this:

Architecture diagram showing AWS Amplify and AWS Lambda hosted in AWS Cloud, with connection to external users from Amplify.

You will notice we added the AWS Lambda service to the diagram, but it does not yet have a connection to AWS Amplify or our users. We will build that out in the next module.

Was this page helpful?

Link Serverless Function to Web App