#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"}}