AWS Lambda and Amazon API Gateway

Deploy a serverless architecture using AWS Lambda and Amazon API Gateway

AWS offers various services to help create a serverless architecture, which allows developers to build and run applications and services without managing infrastructure. In this blog, we’ll explore how to create a serverless architecture using AWS services, such as AWS Lambda and Amazon API Gateway. This setup, aligned with the AWS Certified Developer Associate Certification, simplifies serverless application development. The certification covers essential AWS services and features, offering hands-on labs and practical examples to boost your skills. Let’s dive into the deployment steps with a simple scenario.

Scenario – Serverless architecture using AWS Lambda and Amazon API Gateway

As a developer, you will create a serverless application to check if people’s names exist in a voter names database. The database resides in DynamoDB, which is an AWS-managed NoSQL database service. The application will handle API requests through the API Gateway, the API will invoke the Lambda function, query the DynamoDB for the presence of a name, and return a response.

Amazon API Gateway is an AWS service for creating, publishing, maintaining, monitoring, and securing REST, HTTP, and WebSocket APIs. AWS Lambda is a serverless computing service used for running event-driven code in the cloud.

Here’s the list of objects you will create during the deployment.

Table. Objects and their names

serverless AWS Lambda setup object names

The deployment process can be divided into four steps:

Step 1. Create a database in DynamoDB

Step 2.  Create and configure Lambda function 

Step 2. Create an API in API Gateway

Step 3. Integrate API Gateway with Lambda and deploy the API

Create a DynamoDB table

Follow these steps to create a table with information on voter names and their voter ID. 

  1. Sign in to the AWS Management Console and open the DynamoDB console.
  2. In the left navigation pane, choose Tables.
  3. Choose Create table.
  4. Enter the Table details as follows:
    1. For Table name, enter Voter_DB.
    2. For Partition key, enter VoterID.
  5. Click Create Table. The table is created.

Next, add attributes such as voter names and voter IDs to the table.

  1. In the DynamoDB console, select the table you’ve created and click Items.
  2. Click Create item>Edit, add the attributes, and save them. The tables with attributes are created.

 DynamoDB table

Create a Lambda Function

Follow these steps to create a Lambda Function in the Lambda console.

  1. In the AWS Management Console, navigate to the Lambda service and click Create function.
  2. Select Author from scratch and enter AddVoterLambda for the function name.
  3. Select the latest Python run time as the runtime. In this scenario, we’ve used Python 3.12.
  4. Expand Change default execution role and select Create a new role from AWS policy template and add Role name as LambdaRole.
  5. For Policy templates, select Simple microservice permissions DynamoD and click Create function.

Next, add code to the Lambda function. 

  1. In the Lambda function code editor, add the following code and click Deploy to create the Lambda function.

import json

import boto3

def lambda_handler(event, context):

    # Extract query string parameters

    query_params = event.get(‘queryStringParameters’)

        # Check if the required parameters are present

    if not query_params or ‘voter_id’ not in query_params:

        return {

            ‘statusCode’: 400,

            ‘body’: json.dumps({‘message’: ‘voter_id query parameter is required’})

        }

        voter_id = query_params[‘voter_id’]

        # Initialize a DynamoDB resource

    dynamodb = boto3.resource(‘dynamodb’)

        # Reference the specific DynamoDB table

    table = dynamodb.Table(‘Voter_DB’)

        # Query the table for the specified voter ID

    response = table.get_item(

        Key={‘VoterID’: voter_id}

    )

    # Check if the item exists in the response

    if ‘Item’ in response:

        voter_name = response[‘Item’].get(‘name’)  # Retrieve VoterName

        if voter_name:  # Check if VoterName exists

            return {

                ‘statusCode’: 200,

                ‘body’: json.dumps({‘message’: f’Voter {voter_name} with ID {voter_id} is a registered voter.’})

            }

        else:

            return {

                ‘statusCode’: 200,

                ‘body’: json.dumps({‘message’: f’Voter ID {voter_id} found, but no name is registered.’})

            }

    else:

        return {

            ‘statusCode’: 404,

            ‘body’: json.dumps({‘message’: f’No voter found with ID {voter_id}.’})

        }

DynamoDB resource

Create REST API in API Gateway

Follow these steps to complete the API-side requirements.

  1. In the AWS Management Console, navigate to API Gateway service and click Create API.
  2. Select REST API and then Build.

Next, create the API resource path

  1. In the API dashboard, click Create Resource.
  2. Enter /voter as the Resource Path and click Create Resource.

Next, create a GET Method.

  1. Select the /voter resource and click Create Method.
  2. Click GET from the dropdown and select integration type as Lambda Function.
  3. Select the AddVoterLambda under the lambda function drop-down menu and click Save and then OK.

Note: You can integrate API Gateway with Lambda by selecting Lambda Proxy Integration or leaving it unchecked. In a proxy integration, the entire client HTTPS request is sent as-is to the Lambda function. In a non-proxy integration, you configure how the parameters, headers, and body of the client request are passed to the event parameter of the Lambda handler function. In this scenario, we’ve used the non-proxy option.

Create REST API in API Gateway

Next, add URL Query String Parameters and mapping templates. 

  1. From the API console go the GET method>Edit Method Request and add the name of your query string and save the changes.

API Gateway

Next, set up a Mapping Template for Path and Query Parameter Handling.

   2 . From the Method Execution pane, click Integration Request>Edit>Mapping templates>Add mapping template and add the following template.

JSON mapping template in AWS API Gateway

Deploy the API

You’ve reached the final stage of deploying and integrating Lambda with API Gateway. Follow these steps to complete the deployment.

  1. From the API Gateway console, select the API you’ve created.
  2. Click Action>Deploy API create a new stage and deploy it.

Deploy API settings in AWS API Gateway

If the deployment is successful, you will see the Invoke URL for the deployed stage. You can use this URL to test the application a web browser or a tool like Postman.

Postman GET request to an AWS API Gateway

Now you’ve successfully integrated Lambda with API Gateway for creating a serverless architecture. Congratulations!

Conclusion:  

Eliminating the need for traditional server management, AWS can be your first choice for deploying a serverless architecture because of the wide range of services it offers. I hope the deployment process explained in this blog using three AWS services—DynamoDB, AWS Lambda, and API Gateway—has given you a basic understanding of building and managing serverless applications. For a thorough exploration of serverless architecture and other AWS services, sign up for the  AWS Certified Developer – Associate course. For additional hands-on experience, you can experiment and implement your serverless scenarios using our AWS hands-on labs and AWS sandboxes.

 

About Anitha Dorairaj

Anitha Dorairaj is a passionate cloud enthusiast. With a strong background in cloud technologies, she leverages her expertise to drive innovative solutions. Anitha's commitment to staying at the forefront of tech advancements makes her a key player in the cloud technology landscape.

Leave a Comment

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

Scroll to Top