2
0

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.

API Gateway+LambdaでJSONを受け取る

Posted at

#API GatewayでHTTP APIを使ってみた
API Gateway(HTTP API)は低レイテンシー、低コストということで使ってみた。
Lambda(Python)でJSONデータを受け取る場合に REST API と HTTP API で取り出し方が違うのでメモする。

#JSONデータ
{
    "operation": "PUT",
    "data": {
        "temp":"28.0",
        "humid":"41.2"
    }
}

##HTTP APIの場合

$ curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"operation": "PUT", "data": {"temp":"28.0","humid":"41.2"}}' https://{API ID}.execute-api.{リージョン}.amazonaws.com/{リソースパス}
# Lambda関数(Python)
import json

def lambda_handler(event, context):
  operation = json.loads(event.get('body', '{}')).get('operation')
  data = json.loads(event.get('body', '{}')).get('data')
  temp = data['temp']
  humid = data['humid']

  print("operation: " + operation)
  print("temp: " + temp)
  print("humid: " + humid)

  return {
    'statusCode': 200,
    'body': json.dumps('OK.')
  }
# lambda_handler 引数eventの中身
event: 
{
    "version": "2.0",
    "routeKey": "POST {リソースパス}",
    "rawPath": "{リソースパス}",
    "rawQueryString": "",
    "headers": {
       省略
       :
    },
    "requestContext": {
       省略
       :
    },
    "body": "{\"operation\":\"PUT\",\"data\":{\"temp\":\"28.0\",\"humid\":\"41.2\"}}",
    "isBase64Encoded": false
}

##REST APIの場合

$ curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"operation": "PUT", "data": {"temp":"28.0","humid":"41.2"}}' https://{API ID}.execute-api.{リージョン}.amazonaws.com/{API デプロイのステージ名}
# Lambda関数(Python)
import json

def lambda_handler(event, context):
  operation = event['operation']
  data = event['data']
  temp = data['temp']
  humid = data['humid']

  print("operation: " + operation)
  print("temp: " + temp)
  print("humid: " + humid)

  return {
    'statusCode': 200,
    'body': json.dumps('OK.')
  }
# lambda_handler 引数eventの中身
event: {"operation": "PUT", "data": {"temp": "28.0", "humid": "41.2"}}
2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?