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.

 Time to complete

5 minutes

 Services used

Implementation

  • Create and Configure Your Lambda Function
    • Python
      1. In a new browser tab, log into the AWS Lambda Console.
      2. Make sure you note what region you are creating your function in. You can see this at the very top of the page, next to your account name.
      3. Click on the orange "Create Function" button.
      4. Under "Function Name" type in HelloWorldFunction.
      5. Select Python 3.8 from the runtime drop-down.

      6. Click on the orange "Create Function" button.

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

      8. Replace the code under "Function Code" 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 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. Click the orange "Save" button at the top of your screen.

      10. Let's test our new function. Click on "Select a test event" at the top of your screen.

      11. From that drop-down menu click on "Configure test events."

      12. Under "Event Name" type HelloWorldTestEvent.

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

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

      14. Click the orange "Create" button a the bottom of the page.

    • JavaScript
      1. In a new browser tab, log into the AWS Lambda Console.
      2. Make sure you note what region you are creating your function in. You can see this at the very top of the page, next to your account name.
      3. Click on the orange "Create Function" button.
      4. Under "Function Name" type in HelloWorldFunction.
      5. Select Node.js 16.x from the runtime drop-down.

      6. Click on the orange "Create Function" button.

      7. You should see a green 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. Click the "Deploy" button located next to the orange "Test" button at the top of the code editor.

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

      11. Under "Event Name" type HelloWorldTestEvent.

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

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

      13. Click the save button to create the test event.

      14. Click 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 into the AWS Lambda Console.
      2. Make sure you note what region you are creating your function in. You can see this at the very top of the page, next to your account name.
      3. Click on the orange "Create Function" button.
      4. Under "Function Name" type in HelloWorldFunction.
      5. Select Java 11 from the runtime drop-down.

      6. Click on the orange "Create Function" button.

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

      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 the JAR file with the updated function code to use here.

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

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

      12. Click the orange "Save" button at the top of your screen.

      13. Let's test our new function. Click on "Select a test event" at the top of your screen.

      14. From that drop-down menu click on "Configure test events."

      15. Under "Event Name" type HelloWorldTestEvent.

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

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

      17. Click the orange "Create" button a the bottom of the page.

  • Test Your Lambda Function
    1. Under the "HelloWorldFunction" section at the top of the page, click the "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 click on "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