首页 > 解决方案 > 如何将 API 调用的输出保存到 DynamoDB?

问题描述

我正在从 AWS 中的 lambda 函数调用 REST API。我在终端收到回复。如何将这些 API 响应存储在 DynamoDB 中。如果这对某些人来说可能显得幼稚,我很抱歉。我是初学者和自学者。

标签: amazon-web-servicesrestlambdaamazon-dynamodb

解决方案


这是基于 Python 的 Lambda 函数的完整工作示例:

# Import AWS (Python version) SDK
import boto3

def lambda_handler(event, context):
    # Construct the client to the DynamoDB service
    client = boto3.client('dynamodb')
    db = boto3.resource('dynamodb')

    table_name = 'my-awesome-table'
    # Table instance
    table = db.Table(table_name)
    
    # Example data to query an entry from the table
    primary_column_name = 'email'
    primary_key = 'john@gmail.com'

    # We get an object for the retrieved table entry
    table_entry = get_table_item(table, primary_column_name, primary_key)

    # Example data to put into the table
    new_entry = {
        'email': 'jack@outlook.com',
        'name': 'Jack Ma',
        'age': 56
    }
    put_table_item(table, new_entry)

# Function to retrieve an entry from the DynamoDB table
def get_table_item(table, primary_column_name, primary_key):
    response = table.get_item(
            Key={
                primary_column_name: primary_key
            }
        )
    
    return response['Item']

# Function to put an entry into the DynamoDB table
def put_table_item(table, item):
    response = table.put_item(
            Item=item
        )
    
    # If there were errors, throw an exception
    if (response['ResponseMetadata']['HTTPStatusCode'] != 200):
        raise Exception('Failed to update table!')


推荐阅读