0Pricing
Serverless Backend with AWS Lambda & API Gateway · 课时

Lambda 与 DynamoDB 集成

开发与 DynamoDB 交互的 Lambda 函数,执行 CRUD 操作,构建数据驱动的无服务器后端

Lambda 与 DynamoDB 集成 是 CoddyKit 上的免费 Serverless Backend with AWS Lambda & API Gateway 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Serverless Backend with AWS Lambda & API Gateway 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Lambda & DynamoDB: The Power Duo

Welcome to integrating AWS Lambda with DynamoDB! This combination is a cornerstone for building powerful, serverless backends.

AWS Lambda provides the compute power to run your code without managing servers, while DynamoDB offers a fast, flexible NoSQL database that scales automatically.

Together, they allow you to create data-driven applications that handle create, read, update, and delete (CRUD) operations efficiently.

Granting Lambda DynamoDB Access

Before your Lambda function can interact with DynamoDB, it needs permission. This is managed through an IAM Role attached to your Lambda function.

The IAM role must have a policy that grants specific DynamoDB actions, such as:

  • dynamodb:PutItem (for creating/updating)
  • dynamodb:GetItem (for reading)
  • dynamodb:UpdateItem (for modifying parts of an item)
  • dynamodb:DeleteItem (for removing items)

Always follow the principle of least privilege: grant only the permissions necessary.

Connecting from Lambda with Boto3

In a Python Lambda function, you'll use the AWS SDK for Python, Boto3, to interact with DynamoDB. First, you need to initialize a DynamoDB client or resource.

The boto3.resource('dynamodb') approach is often preferred as it provides a higher-level, object-oriented interface.

Try running this example to see how to initialize the client:

import boto3
import json

def lambda_handler(event, context):
    # Initialize DynamoDB resource
    dynamodb = boto3.resource('dynamodb')
    table_name = 'my-coddykit-table' # Placeholder
    table = dynamodb.Table(table_name)

    print(f"Connected to table: {table_name}")

    return {
        'statusCode': 200,
        'body': json.dumps('DynamoDB client initialized!')
    }

# For local testing/runnable snippet
if __name__ == '__main__':
    print("Running handler locally...")
    lambda_handler({}, {})

Creating & Replacing Items (PutItem)

The put_item() method is used to create a new item or completely replace an existing item in a DynamoDB table.

  • If an item with the same primary key already exists, put_item() will overwrite it entirely.
  • If no item with that primary key exists, it will create a new one.

This operation is useful when you want to ensure an item exists with specific attributes, or you need to replace all its attributes.

PutItem in Action

Here's a Lambda function demonstrating how to use put_item() to add or update an item. We'll use a placeholder table name and item details from the event.

Run the code to see the simulated item creation!

import boto3
import json

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    # Use a placeholder table name
    table = dynamodb.Table('my-coddykit-table')

    item_id = event.get('itemId', 'P001')
    item_name = event.get('itemName', 'New Product')

    table.put_item(
        Item={
            'itemId': item_id,
            'itemName': item_name,
            'category': 'Electronics'
        }
    )
    print(f"Added/updated item: {item_id}")
    return {
        'statusCode': 200,
        'body': json.dumps(f'Item {item_id} processed!')
    }

# For local testing/runnable snippet
if __name__ == '__main__':
    mock_event = {'itemId': 'P002', 'itemName': 'Coddy Phone'}
    lambda_handler(mock_event, {})

Reading Items (GetItem)

To retrieve a single item from a DynamoDB table, you use the get_item() method. This operation requires you to provide the full primary key of the item.

If your table has a simple primary key (only a Partition Key), you'll provide just that value. If it has a composite primary key (Partition Key and Sort Key), you must provide both.

get_item() is highly efficient for direct lookups.

GetItem in Action

This Lambda function shows how to retrieve an item using its itemId (assuming it's our primary key). The response will contain the item's attributes if found.

Run this example to see how get_item() works.

import boto3
import json

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    # Use a placeholder table name
    table = dynamodb.Table('my-coddykit-table')

    item_id = event.get('itemId', 'P001') # Assume 'itemId' is the primary key

    response = table.get_item(
        Key={'itemId': item_id}
    )
    item = response.get('Item')

    if item:
        print(f"Found item: {item}")
        return {
            'statusCode': 200,
            'body': json.dumps(item)
        }
    else:
        print(f"Item {item_id} not found.")
        return {
            'statusCode': 404,
            'body': json.dumps(f'Item {item_id} not found.')
        }

# For local testing/runnable snippet
if __name__ == '__main__':
    mock_event = {'itemId': 'P002'} # Try to get an item
    lambda_handler(mock_event, {})

Modifying Parts of an Item (UpdateItem)

The update_item() method allows you to modify specific attributes of an existing item without replacing the entire item.

This is more efficient than put_item() if you only need to change a few attributes. It requires an UpdateExpression to specify which attributes to modify and how.

Update expressions can add, set, remove, or delete attributes.

Removing Items (DeleteItem)

To delete an item from a DynamoDB table, you use the delete_item() method. Similar to get_item(), you must provide the full primary key of the item you wish to remove.

Once an item is deleted, it cannot be recovered through this operation. Be cautious when using delete_item(), especially in production environments.

Quick Check: DynamoDB Operations

You need to create a new user profile in your DynamoDB Users table. If a user with the same ID already exists, you want to completely overwrite their old profile with the new data. Which Boto3 method should your Lambda function use?

Recap: Lambda & DynamoDB Integration

Great job! You've learned how to integrate AWS Lambda with DynamoDB to build data-driven serverless applications.

  • We covered the importance of IAM permissions for secure access.
  • You saw how to use the Boto3 SDK to connect from Python Lambda.
  • We explored the core CRUD operations: put_item() (create/replace), get_item() (read), update_item() (modify), and delete_item() (remove).

This knowledge is crucial for developing robust serverless backends!

常见问题解答

「Lambda 与 DynamoDB 集成」课时是免费的吗?

是的 — 「Lambda 与 DynamoDB 集成」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Serverless Backend with AWS Lambda & API Gateway 课程的其余内容,请升级到 CoddyKit PRO。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。

「Lambda 与 DynamoDB 集成」这节课中我会学到什么?

开发与 DynamoDB 交互的 Lambda 函数,执行 CRUD 操作,构建数据驱动的无服务器后端 你通过在浏览器中直接运行的动手代码来练习 Serverless Backend with AWS Lambda & API Gateway,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Serverless Backend with AWS Lambda & API Gateway 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Serverless Backend with AWS Lambda & API Gateway 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「Lambda 与 DynamoDB 集成」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Serverless Backend with AWS Lambda & API Gateway 课中编写并运行代码吗?

能。每节 Serverless Backend with AWS Lambda & API Gateway 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. DynamoDB 简介
  2. 设计 DynamoDB 表
  3. Lambda 与 DynamoDB 集成
  4. 使用二级索引查询:GSI 与 LSI
← 返回 Serverless Backend with AWS Lambda & API Gateway