Aws

DynamoDB + ApiGateway를 이용해서 Serverless API 만들어보기

wngnl05 2024. 12. 27. 14:55

URL

ApiGateway를 만들어줍니다.

Method 유형은 "POST"로 작성하고

"통합 유형"은 AWS 서비스를 선택해줍니다.  서비스는 "DynamoDB"를 선택해줍니다.

"작업 이름"은 "GetItem", "PutItem", "UpdateItem", "DeleteItem" 중 하나를 선택하여 넣어줍니다.

 

아래의 코드를 그대로 사용한다 할때 DynamoDB 테이블을 생성할때 파티션 키를 name로 설정해야 합니다.

 

GetItem

더보기

POST로 받은 name의 값이 DynamoDB Table에서 같은 값을 찾아서 반환해줍니다.

< 통합 요청 매핑 탬플릿 >

{ 
  "TableName": "wsi-table",
  "Key": {
    "name": { 
      "S": "$input.params('name')"
    }
  }
}

< 통합 응답 매핑 탬플릿 >

#set($inputRoot = $input.path('$'))
{
  "name": "$inputRoot.Item.name.S",
  "age": "$inputRoot.Item.age.N",
  "country": "$inputRoot.Item.country.S"
}

PutItem

더보기

POST로 받은 name, country 값을 DynamoDB Table애 삽입합니다.

< 통합 요청 매핑 탬플릿 >

{ 
  "TableName": "wsi-table",
  "Item": {
        "name": {
            "S": "$input.path('$.name')"
        },
        "age": {
            "N": "$input.path('$.age')"
        },
        "country": {
            "S": "$input.path('$.country')"
        }
    }
}

< 통합 응답 매핑 탬플릿 >

{ "msg": "Finished" }

DeleteItem

더보기

POST로 받은 name의 값을 DynamoDB에서 삭제합니다.

< 통합 요청 매핑 탬플릿 >

{ 
  "TableName": "wsi-table",
  "Key": {
    "name": { 
      "S": "$input.params('name')"
    }
  }
}

PAY_PER_REQUEST

{msg: Finished}

{name: skills, age:19, country: korea}

{msg: Deleted}

{status: ok}

echo "-------------"
aws dynamodb describe-table --table-name wsi-table --query "Table.BillingModeSummary.BillingMode"
echo "-------------"
API=$(aws apigateway get-rest-apis --query "items[?name=='wsi-api'].id" --output text)
URL=https://$API.execute-api.ap-northeast-2.amazonaws.com/v1/

aws dynamodb scan --table-name wsi-table \
    --projection-expression "#n" \
    --expression-attribute-names '{"#n": "name"}' \
    --select "SPECIFIC_ATTRIBUTES" \
    --query "Items[].name" \
    --output text | xargs -I {} aws dynamodb delete-item --table-name wsi-table --key "{\"name\": {\"S\": \"{}\"}}"

curl -sS -X POST -H "Content-Type: application/json" -d '{"name": "skills", "age": 19, "country": "korea"}' $URL/user
echo "-------------"
curl -X GET $URL/user?name=skills
echo "-------------"
curl -X DELETE $URL/user?name=skills
echo "-------------"
curl -X GET $URL/healthz