LoginSignup
2
2

More than 5 years have passed since last update.

LambdaにAPI Gatewayのステージ名を渡す

Posted at

こんにちはsekitakaです。

Lambda関数を起動したAPI GatewayのAPIのステージによって、Lambda上の処理を変えたい場合があると思います。
そこで今回はLambdaへAPI Gatewayのステージ名を渡す方法を紹介したいと思います。

LambdaにAPI Gatewayのステージ名を渡す手順

  1. API Gatewayの任意のAPIを選択→統合リクエスト→本文マッピングテンプレート
  2. Content-Typeはapplication/jsonを例に説明します。
{
  "stage" : "$context.stage"
}

このようにstage"$context.stage"を記述することでLambda関数にステージ名を渡すことができます。swagger定義ファイルを使用している場合も同様に記述できます。
3. Lambdaでは以下のようにハンドラの引数eventを経由してステージ名にアクセスすることができます。

handler.py
def lambda_handler(event, context):
    stage = event.get('stage') # ステージ名を取得
    if stage == 'hoge':
        # 何かする
        pass

参考

公式ドキュメントにも記載がありますが、$contextを経由して他にも色々な値をLambdaに渡すことができます。

まとめ

いかがでしたでしょうか。このようにAPIの環境や状態によって処理を分けたい場合は$contextを経由することで実現できます。

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