Enterprise Java

AWS Lambda with API Gateway

In a previous post I showed you how to create and deploy an AWS Lambda. We will continue that work and look at updating just the code for that lambda. We will also add a REST endpoint to the AWS Lambda using AWS API Gateway.

So before you continue … if you haven’t already, please follow the instruction in the previous post to make sure you have a running AWS Lambda instance.

Step 1: Update your lambda

Paste the following in update-lambda.sh

01
02
03
04
05
06
07
08
09
10
11
12
#!/bin/bash
 
### Create the lambda package
zip -j helloworld.zip *.py
 
function_name="helloworld"
package_file=helloworld.zip
 
### Update the lambda code
aws lambda update-function-code \
  --function-name $function_name \
  --zip-file fileb://$package_file

or for Java

01
02
03
04
05
06
07
08
09
10
11
12
#!/bin/bash
 
### Create the lambda package
mvn package
 
function_name="helloworld"
package_file="target/lambda-java-example-1.0-SNAPSHOT.jar"
 
### Update the lambda code
aws lambda update-function-code \
   --function-name $function_name \
   --zip-file fileb://$package_file

Make the script executable chmod +x update-lambda.sh and update your lambda ./update-lambda.sh.

Step 2: Pass something to your lambda

Now that we know how to update the lambda in the cloud, lets make a change so we can pass something as a parameter. Rather than saying “hello world!” we want it to say hello to whomever.

In Python:

1
2
def lambda_handler(event, context):
    return "Hello {}!".format(event['to'])

or like the following in Java:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
package example;
 
import com.amazonaws.services.lambda.runtime.Context;
 
public class Hello {
  public String lambdaHandler(Request request, Context context) {
    return "Hello " + request.getTo() + "!";
  }
}
 
class Request {
  private String to;
  public void setTo(String to) { this.to = to; }
  public String getTo() { return to; }
}

Step 3: Tell the lambda to say hello to whomever

1
aws lambda invoke --invocation-type RequestResponse --function-name helloworld --payload '{"to": "whomever"}' output.txt

You should see Hello whomever! in output text

Step 4: Lets add the rest API

Paste the following script into a file such as create-api.sh, change permissions for the file to execute, and execute the script. Take a deep breath …

Note: this script expects the AWS_REGION and AWS_ACCOUNT_ID environment variables to be defined

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/bin/bash
set -e
 
region=$AWS_REGION
account_id=$AWS_ACCOUNT_ID
 
echo "Creating a new API and capturing it's ID ..."
api_id=$(aws apigateway create-rest-api \
   --name HelloWorldAPI \
   --description "Hello World API" \
   --output text \
   --query 'id')
echo "> API ID is: $api_id"
 
echo "Storing the API ID on disk - we'll need it later ..."
echo $api_id > api_id.txt
 
echo "Geting the root resource id for the API ..."
root_id=$(aws apigateway get-resources \
   --rest-api-id "${api_id}" \
   --output text \
   --query 'items[?path==`'/'`].[id]')
echo root_id=$root_id
 
echo "Creating a resource for the /hello path"
resource_id=$(aws apigateway create-resource \
  --rest-api-id "${api_id}" \
  --parent-id "${root_id}" \
  --path-part hello | jq -r .id)
echo "Resource id is $resource_id"
 
echo "Creating the GET method on the /hello resource"
aws apigateway put-method \
  --rest-api-id "${api_id}" \
  --resource-id "${resource_id}" \
  --http-method GET \
  --authorization-type NONE
 
echo "Integrating the GET method to lambda. Note that the request tempalate uses API Gateway template language to pull in the query parameters as a JSON event for the lambda."
aws apigateway put-integration \
  --rest-api-id "${api_id}" \
  --resource-id "${resource_id}" \
  --http-method GET \
  --type AWS \
  --request-templates '{ "application/json": "{\n  #foreach($param in $input.params().querystring.keySet())\n    \"$param\": \"$util.escapeJavaScript($input.params().querystring.get($param))\" \n   #end\n  }" }' \
  --integration-http-method POST \
  --uri arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${region}:${account_id}:function:helloworld/invocations
 
echo "Creating a default response for the GET method"
aws apigateway put-method-response \
  --rest-api-id "${api_id}" \
  --resource-id "${resource_id}" \
  --http-method GET \
  --status-code 200
 
echo "Creating a default response for the integration"
aws apigateway put-integration-response \
  --rest-api-id "${api_id}" \
  --resource-id "${resource_id}" \
  --http-method GET \
  --status-code 200 \
  --selection-pattern ".*"
 
echo "Adding permission for the API to call the lambda for test so we can use the console to make the api call"
aws lambda add-permission \
  --function-name helloworld \
  --statement-id apigateway-helloworld-get-test \
  --action lambda:InvokeFunction \
  --principal apigateway.amazonaws.com \
  --source-arn "arn:aws:execute-api:${region}:${account_id}:${api_id}/*/GET/hello"
 
echo "Adding permission for the API to call the lambda from any HTTP client"
aws lambda add-permission \
  --function-name helloworld \
  --statement-id apigateway-helloworld-get \
  --action lambda:InvokeFunction \
  --principal apigateway.amazonaws.com \
  --source-arn "arn:aws:execute-api:${region}:${account_id}:${api_id}/api/GET/hello"
 
echo "Creating a deployment"
aws apigateway create-deployment \
  --rest-api-id "${api_id}" \
  --stage-name api
 
echo "All done! you can invoke the api on https://${api_id}.execute-api.${region}.amazonaws.com/api/hello?to=whomever"

Step 5: Invoke the API

The last output of the scripts provides the URL that you can paste into the browser. You should see the response “Hello whomever!” once you hit enter in the brower.

Step 6: The Cleanup

You can use the delete.sh script created in the previous post to delete the lambda. To delete the api: Paste the following script and execute as as per usual.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
#!/bin/bash
echo "Reading API id that I store in my create-api script"
api_id=$(<api_id.txt)
 
echo "Removing the permissions from the lambda"
aws lambda remove-permission \
  --function-name helloworld \
  --statement-id apigateway-helloworld-get
aws lambda remove-permission \
  --function-name helloworld \
  --statement-id apigateway-helloworld-get-test
 
echo "Deleting the API"
aws apigateway delete-rest-api \
  --rest-api-id "${api_id}"

Step 7: Relax … its over ;)

… for now!!!

Reference: AWS Lambda with API Gateway from our JCG partner  Mashooq Badar at the Crafted Software blog.
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Mashooq Badar

Mash is a software craftsman with extensive experience in developing innovative solutions and running large scale enterprise projects. For many years he was a Principal Consultant leading some of the most diverse projects for clients in Government, Media and Finance. Before Codurance Mash was a Director at UBS leading a 4 million pounds a year project with 6 development teams situated in London and Krakow. He started the project from scratch, building the teams a developer at a time.Mash is an associated organiser for LSCC, involved since the beginning helping with organisation and running hands-on sessions. Mash has a passion for developing; teams that are skillful and passionate, solutions that are innovative and simple, and software that is aligned to it's business and flexible to change.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button