1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS Lambda で API Gateway 経由して Python で GET パラメータを受け取る

Posted at

Lambda でも下記の方法でGETパラメータを取得できます。

lambda_function.py
import json

def lambda_handler(event, context):
    # TODO implement

    # イベントとコンテキストの内容を出力
    print( "event:" , event )
    print( "context:", context )

    # パラメータを取得する
    strParam1 = event.get('queryStringParameters').get('param1')
    strParam2 = event.get('queryStringParameters').get('param2')

    # パラメータの内容を出力する
    print( "strParam1:", strParam1 );
    print( "strParam2:", strParam2 );

    return {
        'statusCode': 200,
        'body': json.dumps('ok')
    }

下記のコマンドで呼び出します。

run.sh
#!/bin/sh

TARGET='https://xxxx.execute-api.ap-northeast-1.amazonaws.com/default/lambda-test-03?param1=aaa&param2=bbb'

API_KEY="XXXX"

curl -o - "${TARGET}" --header "x-api-key:${API_KEY}"

実行結果として CloudWatch に下記のログが出力されます。

strParam1: aaa
strParam2: bbb

パラメータがない場合はどうなるか。

run.sh
#!/bin/sh

TARGET='https://xxxx.execute-api.ap-northeast-1.amazonaws.com/default/lambda-test-03'

API_KEY="XXXX"

curl -o - "${TARGET}" --header "x-api-key:${API_KEY}"

実行結果

$ sh run.sh
{"message": "Internal server error"}

CloudWatch に下記のエラーログが出力されていました。

[ERROR] AttributeError: 'NoneType' object has no attribute 'get'
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 9, in lambda_handler
    strParam1 = event.get('queryStringParameters').get('param1')
lambda_function.py
    strParam1 = event.get('queryStringParameters').get('param1')
                           ^^^^^^^^^^^^^^^^^^^^^ の項目自体が来ない

queryStringParameters の項目自体があるかないかを確認してハンドリングする必要がります。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?