0
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 3 years have passed since last update.

Python3: 加算をする API

Posted at

AWS APIGateway と Lambda を使って加算をするプログラムを作成します。

Lambda のプログラム

sumup_function.py
# -*- coding: utf-8 -*-
#
#	sumup_function.py
#
#					Sep/25/2021
#
# --------------------------------------------------------------------
import sys
import json
 
# --------------------------------------------------------------------
def lambda_handler(event, context):
	sys.stderr.write("*** lambda_handler *** start ***\n")
	print("Received event: " + json.dumps(event, indent=2))
	print("event['aa'] = " + str(event['aa']))
	print("event['bb'] = " + str(event['bb']))
	aa = int(event['aa'])
	bb = int(event['bb'])
	sum = aa + bb
	rvalue = {}
	rvalue['aa'] = aa
	rvalue['bb'] = bb
	rvalue['sum'] = sum
	sys.stderr.write("*** lambda_handler *** end ***\n")
#
	return rvalue
#
	#raise Exception('Something went wrong')
# --------------------------------------------------------------------

ローカルでのプログラムの動作確認

python-lambda-local -f lambda_handler sumup_function.py event.json
event.json
{
  "aa": 25,
  "bb": 72
}

AWS Lambda にアップロード

必要なロール
role_lambda_sep25
は作成済みとします。

create_lambda.sh
#
NAME="sumup_function"
#
zip -r ${NAME}.zip ${NAME}.py
#
aws lambda create-function \
    --function-name ${NAME} \
    --runtime python3.9 \
    --role arn:aws:iam::123495704257:role/role_lambda_sep25 \
    --handler sumup_function.lambda_handler \
    --zip-file fileb://${NAME}.zip \
    --region ap-northeast-1
#

APIGateway の作成

restapi_create.sh
aws apigateway create-rest-api --name 'Sumup AAA' \
    --region ap-northeast-1

Method の作成

POST の Method は AWS のコンソールで行います。
方法はこちら
API Gateway から Lambda にアクセスする

デプロイ

やはり、AWS のコンソールで行います。

##テスト##
URL の呼び出し が
https://1234ucmnfhj.execute-api.ap-northeast-1.amazonaws.com/Test
とします。

HTTPie

http_test.sh
URL="https://1234ucmnfhj.execute-api.ap-northeast-1.amazonaws.com/Test"
http $URL < event.json

curl

curl_post.sh
URL="https://1234ucmnfhj.execute-api.ap-northeast-1.amazonaws.com/Test"
curl -X POST $URL -d@event.json
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?