0
0

More than 1 year has passed since last update.

serverless frameworkで作成したAPIでLambdaに送信した値を取得。

Last updated at Posted at 2022-08-22

はじめに

Lambdaの引数から値を受信する方法を記載していく。

メイン

dynamoDBになんやかんやするときに、使えるので書いてみた。

パスから取得する

serverless frameworkでGETメソッドのAPIを作成するソースが以下になる。
API作成時のパスは、「https://{APIのId}.execute-api.{Resion}.amazonaws.com/dev/get/{id}」 のようになり、{id}の部分に渡したい値を書く。

functions.yml
function:
 get:
  handler: get.get
  events:
    - http:
        path: get/{id}
        method: get
        # 統合サービスをLambdaにする
        integration: lambda

取得方法は、

get.py
def get(event, context):
  # pathに{}で指定した値が入っている。
  path = event["path"]
 #pathの中にある["id"]から取得できる。
  id = path["id"]
  return id

postした値から取得する

serverless frameworkでPOSTメソッドのAPIを作成するソースが以下になる。
API作成時のパスは、「https://{APIのId}.execute-api.{Resion}.amazonaws.com/dev/create」 になる。

functions.yml
create:
  handler: create.create
  events:
    - http:
        path: create
        method: post
        # 統合サービスをLambdaにする
        integration: lambda

今回postするのは、

{
    "name": "佐藤太朗",
    "age": 7
}

取得方法は、

create.py
def create(event, context):
  # bodyにjsonで送信した値が入っている。
  body = event["body"]
  #bodyの中にある["age"]から取得できる。
  age = body["age"]
  #bodyの中にある["name"]から取得できる。
  name = body["name"]
  return body

実際に記事探すより、検証してみたほうが速かった。トホホ…

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