Backgroud I have more chances to hear about serverless applications using AWS Lambda, so I tried making it.
Preparetion
↓ ↓import json
def lambda_handler(event, context):
request = "[inner_test]"
num = 30
doc = {
"message":'Hello from Lambda!',
"request":process(num)
}
# TODO implement
return {
'statusCode': 200,
'body': json.dumps(doc)
}
def process(src):
if src % 15 == 0:
return "FizzBuzz"
elif src % 5 == 0:
return "Buzz"
elif src % 3 == 0:
return "Fizz"
else :
return src
After writing, press "Deploy"-> "Test".
Then ... The execution result is output in the log.
Development (with API Gateway) The previous configuration was only lambda, but here I will make a request from the outside using API Gateway.
First, select API Gateway from the trigger. Security is your choice.
Select "Stage"-> "POST" to get the URL.
The structure of the URL itself is https: // {restapi_id} .execute-api. {region} .amazonaws.com/ {stage_name} /
So, get the value requested by lambda and FizzBuzz. Speaking in the codebase, it parses event ["body "]
with json and gets the input value.
import json
def lambda_handler(event, context):
request = "[inner_test]"
num = 30
#Supports API Gateway
#Get the value of the request here
if "body" in event.keys():
request = json.loads(event["body"])
num = request["num"]
doc = {
"message":'Hello from Lambda!',
"request":process(num)
}
# TODO implement
return {
'statusCode': 200,
'body': json.dumps(doc)
}
def process(src):
if src % 15 == 0:
return "FizzBuzz"
elif src % 5 == 0:
return "Buzz"
elif src % 3 == 0:
return "Fizz"
else :
return src
Try hitting the API using Postman to see if the fizzbuzz value is actually returned.
If you change the value of num
, either Fizz``Buzz``FizzBuzz
or a number will be returned.
It's done.
Future I thought I should use the minimum VPS and drop the necessary packages without saying serverless, but I could do it in no time. If you link with S3 after lambda processing, it seems that you can leave the data.
Reference Call REST API on Amazon API Gateway
Recommended Posts