Write Your First AWS Lambda in Java
Learn how to create your first Lambda handler in Java using AWS SDK
Join the DZone community and get the full member experience.Join For Free
So far, I have been writing Lambda function in Python for all my AWS projects. In Python its easy, just import boto3 module and starting coding. Things are bit different when you write Lambda handlers in Java. Lets explore and see how you can write a simple HelloWorld Lambda handler in java. I have planned couple of how-to projects that I am going to write in Java. Hence I thought to do HelloWorld post before we dive into complex handlers. Feel free to follow me on twitter for upcoming updates.
To implement handler, we are going to use Maven, Eclipse and AWS SDK for Java. Below are the version:
- Java: 1.8.
- Eclipse: Version: 2020-06 (4.16.0).
- AWS SDK: 2.14.11.
- Maven: 3.6.3 (Included with eclipse).
To get started, create a new empty maven project in eclipse. Go to File-> New-> Maven Project. In the new project dialog box, select "create simple project" and hit next. On next screen. add appropriate information about the project and hit finish. For example:
Now your project is created. Open pom.xml and add following code.
We are setting some properties in
<properties> tag like AWS SDK version and Java Version. We are adding AWS SDK dependency and Lambda core dependency with desired version. The Google JSON dependency is added to convert between JSON and Java object and vice versa. In plugins, we define maven compiler plugin to compile the code and another important plugin called
maven-shade-plugin. This plugin helps to create fat jar a.k.a Uber jar. This jar will contain all the dependencies that are required to successfully run the lambda function.
Now let's create the handler.
Here we are implementing
RequestHandler that will accept a
String and outputs a
String response. The handler is not doing much. Just logging some stuff from
event and in response it sends
200 OK string. After this, right click on project, go to 'Run as' and click 'Maven build'. A configuration window will open. In 'Goals' type
package and hit 'Run' . Build should be successful and will create a fat jar in
Now, go to the AWS console and create a new Lambda function with Java 8 as runtime and upload this jar from Function Code section. In Basic Settings, you have to specify
package.class::methodName in the handler text box. To test this Lambda, create a test event and execute the test.
The output might look similar to this:
Here we complete our first Lambda handler in Java. In next post we will see how we can implement API using AWS SDK.
Published at DZone with permission of Rajan Panchal. See the original article here.
Opinions expressed by DZone contributors are their own.