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

Developing RESTful APIs With Microservices in Java

DZone's Guide to

Developing RESTful APIs With Microservices 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

Learn how modern cloud architectures use of microservices has many advantages and enables developers to deliver business software in a CI/CD way.

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 with which you can run your Java code to provide the main functionality of your service. For more information on Lambda, please visit this link.

Amazon API Gateway is [art of a networking service 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 them with Lambda functions. The data passes from the API endpoint to the Lambda function and is handled by the API Gateway. To read more about API Gateway, please visit this link.

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

Prerequisites

First, you need to have a development machine ready, for which you need Java 8, Eclipse IDE, and AWS Toolkit for Eclipse. Complete details on how to do this can be found here.

Step 1: Create a Lambda Function

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...”

Eclipse Java Lambda new project.png

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

Eclipse Java Lambda new project stream request handler.png

After hitting “Finish,” sample code will be loaded into your newly created project. Open the main handler function and update 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;
   }
}

Build and deploy this Lambda function. Complete information on deploying a Java Lambda function 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

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

Click “Create API”.

Select “New API” and provide “API name”

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

API Gateway create resource.png

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

From the next screen, which shows settings for the “Any” method, select “Lambda Function” as the integration type. Make sure to select “Use Lambda Proxy integration” as well. Select the region where you deployed your Lambda function and input the Lambda name.

API Gateway add method.png

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

API Gateway deploy API.png

Select [New Stage] and provide a 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.

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 for this tutorial:

  • 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 as follows:

API Gateway sample output.png

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. Following this simple tutorial, you should be able to get started developing serverless microservices on AWS using Java.

Discover how to deploy pre-built sample microservices OR create simple microservices from scratch.

Topics:
aws lambda ,serverless ,java ,tutorial ,api gateway ,microservices

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}