P
Cloud Blog ProAWS Blog · Cộng đồng VN
Build API Gateway with Lambda Integration connect DynamoDB

Build API Gateway with Lambda Integration connect DynamoDB

MBMinh Bùi··5 phút đọc·268 lượt xem

Lab Details

  1. You will practice using Amazon API Gateway, Lambda and DynamoDB.
  2. Duration: 20 minutes
  3. AWS Region: US East (N. Virginia) us-east-1

Architecture Diagram

Images

Task Details

  1. Create dynamodb table
  2. Create lambda
    • Tạo role cho lambda access đến dynamo db
    • Tạo lambda create user
    • Tạo lambda get user
  3. Create api gateway
    • Tạo resource: user
    • Tạo method POST cho resource user
    • Tạo method GET cho resource user
    • Deploy API lên dev stage
  4. Test API

Create DynamoDB Table

Truy cập vào service DynamoDB -> nhấn Create Table

  • Table name: d-saa-dynamodb
  • Partition Key: PK
  • Sort Key: để trống
  • Table settings: Chọn Default settings

Create Lambda

Create role cho lambda có quyền access đến DynamoDB

Create IAM Role với các parameter sau:

  • Use case: Lambda
  • Policy:
    • AmazonDynamoDBFullAccess_v2 (policy này cho phép full quyền thao tác với DynamoDB)
    • AWSLambdaBasicExecutionRole (policy này cho phép Lambda có các quyền cơ bản như xuất log ra CloudWatch để debug)
  • Role name: d-saa-lambda-role

Kết quả:

Create Lambda function: create-user (Lambda tạo user vào DynamoDB)

Tại Console Lambda -> Event Functions -> Create Event Function

  • Author from scratch
  • Basic information
    • Function name: d-saa-lambda-create-user
    • Runtime: Python 3.xx(chọn phiên bản mới nhất)
    • Architecture: arm64
    • Custom execution role: d-saa-lambda-role

Update source code cho lambda

# Lambda nhận "name" từ API Gateway, tạo PK duy nhất và lưu vào DynamoDB

import boto3   # AWS SDK cho Python
import uuid    # Tạo ID duy nhất
import json    # Xử lý JSON

# Kết nối tới bảng DynamoDB (khởi tạo ngoài handler để tái sử dụng)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('d-saa-dynamodb')

def lambda_handler(event, context):
    # Lấy body (dạng chuỗi JSON) và chuyển thành dict
    strBody = event.get('body')
    param = json.loads(strBody)
    name = param['name']

    # Tạo khóa chính dạng "USER#<uuid>"
    pk = f"USER#{str(uuid.uuid4())}"

    # Bản ghi cần lưu
    item = {
        'PK': pk,
        'Name': name
    }

    # Ghi vào DynamoDB
    table.put_item(Item=item)

    # Trả kết quả HTTP 200 kèm PK
    response = {
        'statusCode': 200,
        'body': f"Data saved with PK: {pk}"
    }

    return response

Nhấn Deploy

Create Lambda function: get-user (Lambda lấy danh sách user từ DynamoDB)

Tương tự tạo function thứ 2:

Tại Console Lambda -> Event Functions -> Create Event Function

  • Author from scratch
  • Basic information
    • Function name: d-saa-lambda-get-user
    • Runtime: Python 3.xx
    • Architecture: arm64
    • Custom execution role: d-saa-lambda-role

Update source code cho lambda

# Lambda đọc toàn bộ dữ liệu trong bảng DynamoDB và trả về dạng JSON

import boto3   # AWS SDK cho Python
import json    # Xử lý JSON

# Kết nối tới bảng DynamoDB (khởi tạo ngoài handler để tái sử dụng)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('d-saa-dynamodb')

def lambda_handler(event, context):
    # Quét (scan) toàn bộ bảng
    response = table.scan()
    items = response['Items']

    # Mỗi lần scan tối đa 1MB, nên lặp tiếp nếu còn dữ liệu (phân trang)
    while 'LastEvaluatedKey' in response:
        response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
        items.extend(response['Items'])

    # Chỉ lấy 2 trường PK và Name cho từng bản ghi
    records = []
    for item in items:
        pk = item['PK']
        name = item['Name']
        record = {'PK': pk, 'Name': name}
        records.append(record)

    # Trả kết quả HTTP 200, body là danh sách bản ghi dạng JSON
    response = {
        'statusCode': 200,
        'body': json.dumps(records)
    }

    return response

Bấm "Deploy"

Create API Gateway

Vào API Gateway Console > APIs > Create API -> REST API > Build

API details:

  • New API
  • API name: d-saa-api
  • API endpoint type: Regional
  • Security Policy: SecurityPolicy_TLS13_1_3_2025_09 (recommended)

Tạo resource: user (các API dành cho thao tác với user)

Create Resource

Recource name: user

Tạo method POST cho resource user

Method details

  • Method type: POST
  • Intergration Type: Lambda Funciton
  • Lambda proxy integration: Enable
  • Lambda region: us-east-1
  • Lambda function: d-saa-lambda-create-user
  • Integration timeout: 29000

Tạo method GET cho resource user

Method details

  • Method type: GET
  • Intergration Type: Lambda Funciton
  • Lambda proxy integration: Enable
  • Lambda region: us-east-1
  • Lambda function: d-saa-lambda-get-user
  • Integration timeout: 29000

Deploy API lên dev stage (môi trường dev)

Quá trình Deploy hoàn tất và bạn sẽ nhận được một URL, copy URL để thực hiện test API nhé!

Test API

Bạn có thể sử dụng 1 tool test API nào đó như Postman cũng ok, nếu chưa có thì có thể test online.

truy cập vào reqbin.com

Test create user

  • URL: Invoke URL + /user
  • Content: JSON
  • Method: POST
{
  "name": "<name tuỳ ý>"
}

Request tạo user thành công sẽ trả về kết quả là UUID của user như hình trên

Test get user

  • URL: Invoke URL + /user
  • Method: GET

Confirm có response trả về là PK và Name như hình trên.

Ngoài ra cũng check DynamoDB để confirm data đã được tạo chính xác.

Vào DynamoDB, chọn table đã tạo, Nhấn Explore table items

Chọn Scan để quét toàn bộ table, nhấn Run và confirm kết quả

Clean up

  • Delete API Gateway: d-saa-api
  • Delete 2 Lambda function
    • d-saa-lambda-create-user
    • d-saa-lambda-get-user
  • Delete Lambda role: d-saa-lambda-role
  • Delete DynamoDB Table: d-saa-dynamod
Quay lại trang chủ

Bình luận