Setting Up AWS Lambda with API Gateway: A Technical Guide

Introduction

This guide walks through the complete process of building a serverless API using AWS Lambda and API Gateway. By following these steps, you'll create a fully functional API that can perform CRUD operations on a DynamoDB database.

Step 1: Create Permissions Policy

  • Create an IAM policy allowing DynamoDB CRUD operations and CloudWatch Logs write access
  • Use JSON policy with specific service actions
  • Name policy lambda-apigateway-policy
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DynamoDBAccess",
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:UpdateItem",
        "dynamodb:DeleteItem",
        "dynamodb:Scan",
        "dynamodb:Query"
      ],
      "Resource": "arn:aws:dynamodb:*:*:table/lambda-apigateway"
    },
    {
      "Sid": "CloudWatchLogsAccess",
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    }
  ]
}
                    

Step 2: Create Execution Role

  • Create an IAM role for Lambda function
  • Attach the previously created lambda-apigateway-policy
  • Role name: lambda-apigateway-role
  • Enables Lambda to interact with DynamoDB and CloudWatch

Step 3: Create Lambda Function

  • Language options: Node.js or Python
  • Function name: LambdaFunctionOverHttps
  • Key implementation details:
    • Define CRUD operations for DynamoDB
    • Use AWS SDK for database interactions
    • Handle different operation types via switch/dictionary
  • Attach lambda-apigateway-role as execution role
// Node.js example
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
const TABLE_NAME = "lambda-apigateway";

exports.handler = async (event) => {
    const operation = event.operation;
    
    switch(operation) {
        case 'create':
            return await createItem(event.payload);
        case 'read':
            return await readItem(event.payload);
        case 'update':
            return await updateItem(event.payload);
        case 'delete':
            return await deleteItem(event.payload);
        default:
            return {
                statusCode: 400,
                body: JSON.stringify({ error: "Unsupported operation" })
            };
    }
};

async function createItem(data) {
    const params = {
        TableName: TABLE_NAME,
        Item: data
    };
    
    try {
        await docClient.put(params).promise();
        return {
            statusCode: 201,
            body: JSON.stringify({ message: "Item created successfully" })
        };
    } catch (err) {
        return {
            statusCode: 500,
            body: JSON.stringify({ error: err.message })
        };
    }
}
                    

Step 4: Create DynamoDB Table

  • Table name: lambda-apigateway
  • Partition key: id (String type)
  • Used for storing and managing data

Step 5: Configure API Gateway

  • Create REST API named DynamoDBOperations
  • Add resource: DynamoDBManager
  • Create POST method
  • Integrate with Lambda function
  • Deploy API to a stage (e.g., test)

Step 6: Test and Invoke

  • Test via AWS Console:
    • Create/Read/Update/Delete items
  • Use curl for HTTP requests
  • Verify operations through DynamoDB console

Best Practices

  • Use environment variables for table names
  • Consider separate Lambda functions for each operation
  • Implement proper error handling
  • Use IAM for secure access management
← Back to Guides