Wednesday, October 18, 2023

AWS SAM template to deploy lamdas function exposing lambda through API Gateway.

This thread discusses the steps to deploy a Lambda function named "getIdentities" with a layer and expose it through API Gateway using AWS SAM.  The Lambda function fetches data from DynamoDB, you can use the following AWS SAM template. This example assumes you're working with Node.js for your Lambda function and DynamoDB as your database:


YAML 

AWSTemplateFormatVersion: '2010-09-09'

Transform: 'AWS::Serverless-2016-10-31'


Resources:

  MyLambdaLayer:

    Type: AWS::Serverless::LayerVersion

    Properties:

      LayerName: MyLayer

      ContentUri: ./layer/

      CompatibleRuntimes:

        - nodejs14.x

      Description: My Lambda Layer


  MyLambdaFunction:

    Type: AWS::Serverless::Function

    Properties:

      Handler: index.handler

      Runtime: nodejs14.x

      Layers:

        - !Ref MyLambdaLayer

      CodeUri: ./function/

      Description: My Lambda Function

      Environment:

        Variables:

          DYNAMODB_TABLE_NAME: !Ref MyDynamoDBTable

      Events:

        MyApi:

          Type: Api

          Properties:

            Path: /getIdentities

            Method: GET


  MyDynamoDBTable:

    Type: AWS::DynamoDB::Table

    Properties:

      TableName: MyDynamoDBTable

      AttributeDefinitions:

        - AttributeName: id

          AttributeType: S

      KeySchema:

        - AttributeName: id

          KeyType: HASH

      ProvisionedThroughput:

        ReadCapacityUnits: 5

        WriteCapacityUnits: 5


Outputs:

  MyApi:

    Description: "API Gateway endpoint URL"

    Value:

      Fn::Sub: "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/getIdentities"

 


In this SAM template:


1. We define a Lambda Layer resource named `MyLambdaLayer`. You should place your layer code in the `./layer/` directory.


2. We define a Lambda function resource named `MyLambdaFunction`. This function uses the layer created in step 1 and is associated with an API Gateway event at the path "/getIdentities" and HTTP method GET. The function code is located in the `./function/` directory, and the handler is set to `index.handler`. We also set an environment variable to specify the DynamoDB table name.


3. We define a DynamoDB table resource named `MyDynamoDBTable` to store your data. Adjust the table name, schema, and provisioned throughput according to your requirements.


4. The Outputs section provides the URL of the API Gateway endpoint where you can invoke the "getIdentities" Lambda function.


Make sure your project directory structure is organized as follows:



project-directory/

  ├── template.yaml

  ├── function/

  │     ├── index.js

  │     └── package.json

  ├── layer/

  │     ├── layer-files

  └── template-configs/

        ├── parameters.json

        ├── metadata.json



To fetch data from DynamoDB, you can use the AWS SDK for JavaScript in your Lambda function code. Here's a simple example of how you can fetch data from DynamoDB using the Node.js SDK:


const AWS = require('aws-sdk');


const dynamodb = new AWS.DynamoDB.DocumentClient();

const tableName = process.env.DYNAMODB_TABLE_NAME;


exports.handler = async (event) => {

  try {

    const params = {

      TableName: tableName,

      Key: {

        id: 'your-key-here',

      },

    };


    const data = await dynamodb.get(params).promise();


    return {

      statusCode: 200,

      body: JSON.stringify(data.Item),

    };

  } catch (error) {

    return {

      statusCode: 500,

      body: JSON.stringify({ error: error.message }),

    };

  }

};



In this code, we're using the AWS SDK to fetch an item from DynamoDB based on a specified key. You should customize the key and error handling based on your use case.

OCI Knowledge Series: OCI Infrastructure components

  Oracle Cloud Infrastructure (OCI) provides a comprehensive set of infrastructure services that enable you to build and run a wide range of...