2
1

More than 3 years have passed since last update.

API Gatewayのlamdba連携時の引数のやり取りについて

Last updated at Posted at 2019-12-24

API-Gatewayとlambdaで引数のやり取りする場合は、全部Stringで渡されるんだね。よく考えたら、QueryParameterの場合もあるし、JSONでやり取りするとは限らないか。

なので、

request.json
{
  "user_id": "string",
  "lang": "string",
  "args": {
    "name": "string",
    "keyWord": "string"
  }
}

こんな感じのjsonをAPI-Gatewayに対してPOSTする場合、lamdba側では、以下のような処理を行う必要がありますね。

sample.py
def lambda_handler(event, context):

    # request bodyはstringなので、jsonに変換する
    body = json.loads(event["body"])
    # こんな感じにすると、user_idが取得できる。
    user_id = body["user_id"]

こうしないと、lambda側で、TypeError: string indices must be integersになります。

またこれは応答時も同様で、JSONはAPI-Gatewayが受け取れないことから、json.dumpsする必要がありますね。

sample.py
    return {
        'statusCode': 200,
        'body': json.dumps({
            'result': result,
            'error_code': error_code,
            'error_message': message})
        }

こっちはAPI-Gateway側で、Execution failed due to configuration error: Malformed Lambda proxy responseになりますね。
https://aws.amazon.com/jp/premiumsupport/knowledge-center/malformed-502-api-gateway/

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1