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

Building Serverless REST API's With Lambda Forest

DZone's Guide to

Building Serverless REST API's With Lambda Forest

Learn to build REST APIs with Lambda Forest, a microplatform that makes common tasks easier while building REST API's using the Lambda Functions and API Gateway.

· Integration Zone
Free Resource

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

During my journey developing REST API's using the AWS Serverless Stack (API Gateway, Lambda, and DynamoDB) I have faced many real world scenarios where writing request validations and some business logic in Lambda Functions can be repetitive and some times painful (especially if you're using API Gateway Proxy Integration).

You start with the idea that a Lambda Function should do only, and only one thing, and should be as small as possible. By the end of the day, if you didn't look carefully, you end up with more than 200 lines of code in a single Lambda Function. To ease the pain of writing repetitive tasks in Lambda Functions, there is a set of tools called lambda-forest.

Lambda Forest

Lambda Forest is a microframework that provides a set of tools to make it easier to develop rest APIs using the AWS Lambda Function and API Gateway. Lambda Forest attempts to make the development faster by easing common tasks, such as:

  • Exception handling,

  • Request body deserialization,

  • Response body serialization, and

  • Request validation.

You can customize the way lambda-forest works by adding your own deserialization/serialization and request validation logic. Also, the microframework provides a way to run your Lambda functions locally.

Building a REST API

Let's build simple REST API.

  1. Create a Maven project with the following dependencies in your pom.xml:

<dependency>
  <groupId>br.com.tdsis</groupId>
  <artifactId>lambda-forest</artifactId>
  <version>0.0.1</version>
</dependency>


2. Add the maven-compiler-plugin, versions-maven-plugin and maven-shade-plugin.

 <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.5.1</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
    </configuration>
</plugin>
<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>versions-maven-plugin</artifactId>
  <version>2.2</version>
</plugin>
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-shade-plugin</artifactId>
  <version>2.4.3</version>
  <configuration>
    <createDependencyReducedPom>false</createDependencyReducedPom>
  </configuration>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>shade</goal>
      </goals>
    </execution>
  </executions>
</plugin>


3. Write the Request Handler

The Lambda Forest framework provides an abstract base class called AbstratRequestHandler that handles a Lambda execution call and perform some operations such as request body deserialization, request validation, response body serialization and exception handling.

Let's write a handler for a POST request with some simple validation:

public class PostUserRequest {

  @Size(min = 3, max = 45)
  private String firstName;

  @Size(min = 3, max = 45)
  private String lastName;

  public String getFirstName() {
  return firstName;
  }

  public void setFirstName(String firstName) {
  this.firstName = firstName;
  }

  public String getLastName() {
  return lastName;
  }

  public void setLastName(String lastName) {
  this.lastName = lastName;
  }

}


public class PostUserResponse {

  private String message;

  public PostUserResponse(String message) {
  this.message = message;
  }

  public String getMessage() {
  return message;
  }

  public void setMessage(String message) {
  this.message = message;
  }

}


public class PostUserHandler extends AbstractRequestHandler<PostUserRequest, PostUserResponse> {

  @Override
  public void before(Context context) throws HttpException {
  addResponseHeader("Access-Control-Allow-Origin", "*");
  }

  @Override
  public PostUserResponse execute(@Valid PostUserRequest input, Context context) throws HttpException {
  String message = String.format("Hello %1s %2s", input.getFirstName(), input.getLastName());
  return new PostUserResponse(message);
  }

}


4. Packing Our JAR file

mvn clean package


5. Create a Lambda Function

Log in to the AWS Management Console, go to the Lambda section and hit "Create a Lambda Function."

In the "Select Blueprint" page, choose "Blank Function."

In "Configure triggers," click "next" and configure your Lambda Function:

Image title

6. Create an API Gateway Resource

Go to the API Gateway section and hit "Create API."

Image title

Under "Actions," select "Create Resource," name your resource, and select "Enable API Gateway CORS."

Image title

Select the resource "/users" and click "Create Method" under the actions menu; we'll create a POST method.

Image title


Select "Deploy API" under the actions menu.

Image title


7. Test the Endpoint

Let's try to make a request that violates the constraints that we have defined in our PostUserRequest class:

curl -X POST -s https://YOUR_API_ID.execute-api.us-east-1.amazonaws.com/v1/users -d '{"firstName": "a", "lastName": "b"}' | python -m json.tool

You'll notice the following response:

{
    "errors": [
        {
            "attribute": "firstName",
            "message": "size must be between 3 and 45"
        },
        {
            "attribute": "lastName",
            "message": "size must be between 3 and 45"
        }
    ],
    "message": "Unprocessable entity"
}

Let's try again with a valid request body:

curl -X POST -s https://YOUR-API-ID.execute-api.us-east-1.amazonaws.com/v1/users -d '{"firstName": "John", "lastName": "Doe"}' | python -m json.tool

This time we get

{
    "message": "Hello John Doe"
}


Conclusion

Lambda Forest is a simple, but powerful microframework that can help easing common tasks while building REST API's using Lambda Functions and API Gateway.

For more information about the lambda-forest project, check the GitHub page.

You can find this sample project at https://github.com/tommelo/serverless-rest-api.

The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:
serverless ,aws ,java ,rest api ,api ,aws lambda

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}