Tạo Lambda Function để Ghi dữ liệu

Tạo Lambda Function mới

  1. Truy cập AWS Lambda Console
    • Chọn Functions từ thanh điều hướng bên trái
    • Nhấn nút Create function

Tạo Lambda Function

  1. Trong trang Create function:
    • Chọn Author from scratch
    • Đặt tên function: book_create
    • Chọn Python 3.11 làm Runtime
    • Nhấn Create function

Cấu hình Lambda Function

Cấu hình Function

  1. Trong giao diện function book_create:
    • Paste code sau vào editor lambda_function.py:
import boto3
import json

client = boto3.resource('dynamodb')
    
def lambda_handler(event, context):
    book_item = event["body"]
    error = None
    
    try:
        table = client.Table('Books')
        table.put_item(Item = book_item)
    except Exception as e:
        error = e
        
    if error is None:
        response = {
            'statusCode': 200,
            'body': 'Ghi dữ liệu vào DynamoDB thành công!',
            'headers': {
                'Content-Type': 'application/json'
            },
        }
    else:
        response = {
            'statusCode': 400,
            'body': 'Ghi dữ liệu vào DynamoDB thất bại!',
            'headers': {
                'Content-Type': 'application/json'
            },
        }

    return response
  • Nhấn Deploy để lưu thay đổi

Cấu hình Code

Cấu hình IAM Permissions

  1. Thêm quyền truy cập DynamoDB:
    • Chọn tab Configuration
    • Chọn Permissions từ menu trái
    • Nhấn vào role của function

Cấu hình IAM

  1. Trong trang IAM Role:
    • Chọn Attach policies
    • Tìm và chọn policy AmazonDynamoDBFullAccess
    • Nhấn Add permissions

Thêm Policy

Kiểm tra Function

  1. Tạo test event:
    • Chọn tab Test
    • Đặt tên event: test_1
    • Nhập JSON test sau:
{
  "body": {
      "id": "1",
      "name": "Java Programming",
      "author": "Alex Smith",
      "category": "Technology",
      "price": "10.89",
      "description": "Hướng dẫn lập trình Java cơ bản",
      "image": "https://book-image-resize-store.s3.amazonaws.com/Java.jpg"
  }
}
  • Nhấn SaveTest

Test Function

Xác nhận dữ liệu trong DynamoDB

  1. Truy cập DynamoDB Console:
    • Chọn bảng Books
    • Chọn Explore table items

Xem DynamoDB

  1. Kiểm tra dữ liệu đã được thêm vào:

Kết quả