Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Developing RESTful APIs in Java

DZone's Guide to

Developing RESTful APIs in Java

Read this post to learn more about developing RESTful APIs in Java with Amazon API Gateway and AWS Lambda.

· Microservices Zone ·
Free Resource

Containerized Microservices require new monitoring. See why a new APM approach is needed to even see containerized applications.

Introduction

AWS Lambda and Amazon API Gateway can be used to create RESTful web services in Java without making complex Java framework configurations or setting up and maintaining web servers, like Tomcat, WebSphere etc. A combination of Lambda and API Gateway makes it very easy for you to develop APIs and also easily manage staging environments like Dev, Test, and Prod for your APIs.

AWS Lambda is a highly scalable and highly available serverless compute platform that you can run your Java code. This will provide the main functionality of your service. For more information on Lambda, please visit this link.

Amazon API Gateway is one of the networking services provided by AWS that allows developers to easily build and deploy API endpoints. It makes it super easy for the developers to create https endpoints and integrate it with Lambda function. The data passes from the API endpoint to the Lambda function and is handled by the API Gateway. To read more about the API Gateway, please visit this link.

This article provides a step-by-step guide on how you can develop RESTful microservices in Java using the Lambda and API Gateway.

Prerequisites

First, you need to have a development machine ready. You will need Java 8, Eclipse IDE, and AWS Toolkit for Eclipse. For complete details on how to do this, more information can be found here.

Step 1: Create a Lambda Function

1. Once you have the Eclipse IDE ready to use, an AWS icon will appear in the main toolbar. Click on it and select “New AWS Lambda Project...”

Image title

2. Provide the appropriate project name and Maven configurations. Select “Stream Request Handler” as the Input type:

Image title

3. After hitting “Finish,” sample code will be loaded into your newly created project. Open the main handler function and update it with the following piece of code:

package com.amazonaws.lambda.demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.Writer;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;

public class LambdaFunctionHandler implements RequestStreamHandler
{
JSONParser parser = new JSONParser();

   @Override
   public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException
   {
    LambdaLogger logger = context.getLogger();
       logger.log("Loading Java Lambda handler of ProxyWithStream");

       String proxy = null;
String param1 = null;
String param2 = null;

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
       JSONObject responseJson = new JSONObject();
       String responseCode = "200";
       JSONObject event = null;

       try {
           event = (JSONObject)parser.parse(reader);
           if (event.get("pathParameters") != null) {
               JSONObject pps = (JSONObject)event.get("pathParameters");
               if ( pps.get("proxy") != null) {
                   proxy = (String)pps.get("proxy");
               }
           }
           if (event.get("queryStringParameters") != null)
           {
               JSONObject qps = (JSONObject)event.get("queryStringParameters");
               if ( qps.get("param1") != null)
               {
                   param1 = (String)qps.get("param1");
               }
           }
           if (event.get("queryStringParameters") != null)
           {
               JSONObject qps = (JSONObject)event.get("queryStringParameters");
               if ( qps.get("param2") != null)
               {
                   param2 = (String)qps.get("param2");
               }
           }

       }
       catch(Exception pex)
       {
        responseJson.put("statusCode", "400");
        responseJson.put("exception", pex);
       }
         // Implement your logic here
       int output = 0;
       if (proxy.equals("sum"))
       {
        output = sum(Integer.parseInt(param1), Integer.parseInt(param2));
       }
       else if (proxy.equals("subtract"))
       {
        output = subtract(Integer.parseInt(param1), Integer.parseInt(param2));
       }

        JSONObject responseBody = new JSONObject();
           responseBody.put("input", event.toJSONString());
           responseBody.put("message", "Output is" + output);

           JSONObject headerJson = new JSONObject();
           headerJson.put("x-custom-header", "my custom header value");
           headerJson.put("Access-Control-Allow-Origin", "*");

           responseJson.put("isBase64Encoded", false);
           responseJson.put("statusCode", responseCode);
           responseJson.put("headers", headerJson);
           responseJson.put("body", responseBody.toString());  

           OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
           writer.write(responseJson.toJSONString());  
           writer.close();
   }
   public int sum(int a, int b)
   {
    return a+b;
   }
   public int subtract(int a, int b)
   {
    return a-b;
   }
}


5. Build and deploy this Lambda function. After that, complete the information on deploying a Java Lambda function. This can be found here.

For this example, we created the Lambda function in the AWS console by the name of “REST_API_HelloWorld.”

Step 2: Create an API Gateway Endpoint

1. Go to the AWS console and launch the API Gateway Service

2. Click “Create API”

3. Select “New API” and provide “API name”

4. After creation of the API, add a Resource, as shown below

Image title

Make sure to check the “Configure as proxy resource” option.

5. For the next screen, it will be showing the settings for the “Any” method. You will need to select the “Lambda Function” as the integration type. Make sure to select “Use Lambda Proxy integration,” as well. Lastly, select the region where you deployed your Lambda function and input the Lambda name.

Image title

6. Now, we will deploy this API to a staging environment. To do this, click on “Action” and select “Deploy API.”

Image title


7. Select [New Stage] and provide the Stage name and description. For this tutorial, we used “Dev” as the staging name. Once the deployment is complete, the console will take you to the staging page.

8. Copy the “Invoke URL” and append it with the proxy resource name and parameters with values that you want to send to your Lambda. See the example below:

Format:

https://5yv20hbz44.execute-api.eu-west-1.amazonaws.com/Dev/{proxy}?{set_of_params_separated_by_&}

Example:

https://5yv20hbz44.execute-api.eu-west-1.amazonaws.com/Dev/sum?param1=100&param2=100

The output of this will be

Image title


Conclusion

Serverless computing platforms, like AWS Lambda, are very popular these days. Many organizations require their DevOps engineers to be able to develop Serverless applications as it reduces the time required to set up the hardware/software infrastructure consequently reducing the project delivery time. So, following this simple tutorial, you should be able to get started with developing serverless microservices on AWS using Java.

Automatically manage containers and microservices with better control and performance using Instana APM. Try it for yourself today.

Topics:
cloud development ,aws lambda ,aws api gateway ,microservice ,serverless ,java ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}