Aws Lambda Java Example Code: Post, Get, Put, Delete

Aws Lambda Java Post example code

Here is an example of an AWS Lambda function written in Java that handles an HTTP POST request and returns a JSON response:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();
        try {
            // parse the post data
            JsonNode postData = objectMapper.readTree((String) input.get("body"));

            // do something with the data
            String name = postData.get("name").asText();
            Response responseBody = new Response("Hello, " + name);

            return ApiGatewayResponse.builder()
                    .setStatusCode(200)
                    .setObjectBody(responseBody)
                    .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                    .build();
        } catch (IOException e) {
            logger.log(e.getMessage());
            return ApiGatewayResponse.builder()
                    .setStatusCode(500)
                    .setObjectBody("Error while parsing input: " + e.getMessage())
                    .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                    .build();
        }
    }
}

In this example, the class MyLambdaFunction implements the RequestHandler interface, which is provided by the AWS Lambda Java SDK. The class takes in two parameters: Map and Context, which represent the input to the function and the runtime context of the function, respectively.

The function uses the ObjectMapper class to parse the request body as a JSON object and extract the name property. It then creates an instance of the Response class with the message “Hello, ” + name and returns it as the response to the request.

You would need to create a new Lambda function in the AWS Lambda console and then upload the JAR file containing this code. After that, you would need to configure an API Gateway trigger to handle the incoming POST request and route it to your Lambda function.

It’s important to note that this is just a basic example and depending on your use case you might need to handle authentication, validation, error handling and other requirements.
You might also need to import the classes used on this example like com.amazonaws.services.lambda.runtime.Context, com.amazonaws.services.lambda.runtime.LambdaLogger, com.amazonaws.services.lambda.runtime.RequestHandler and other.

Aws Lambda Java Get Header example code

Here is an example of an AWS Lambda function written in Java that retrieves and parses headers from an HTTP request:

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

import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();

        // Retrieve headers from input
        Map headers = (Map)input.get("headers");

        // Parse specific header
        String myHeader = headers.get("my-header");

        // Do something with the header value
        Response responseBody = new Response("Hello, " + myHeader);

        return ApiGatewayResponse.builder()
                .setStatusCode(200)
                .setObjectBody(responseBody)
                .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                .build();
    }
}

This example retrieves the headers from the input object, which is passed as the first argument to the Lambda function. It then uses the get() method to retrieve the value of a specific header, in this case “my-header”, and save it to a variable. Then the function creates an instance of the Response class with the message “Hello, ” + myHeader and returns it as the response to the request.

You would need to create a new Lambda function in the AWS Lambda console and then upload the JAR file containing this code. After that, you would need to configure an API Gateway trigger to handle the incoming GET request and route it to your Lambda function.

It’s important to note that this is just a basic example and depending on your use case you might need to handle authentication, validation, error handling and other requirements.
You might also need to import the classes used on this example like com.amazonaws.services.lambda.runtime.Context, com.amazonaws.services.lambda.runtime.LambdaLogger, com.amazonaws.services.lambda.runtime.RequestHandler and other.

Aws Lambda Java get Example code

Here is an example of an AWS Lambda function written in Java that handles an HTTP GET request and returns a JSON response:

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

import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();

        // Retrieve query string parameters
        Map queryParams = (Map)input.get("queryStringParameters");

        // Retrieve name
        String name = queryParams.get("name");

        // Do something with the query string parameters
        Response responseBody = new Response("Hello, " + name);

        return ApiGatewayResponse.builder()
                .setStatusCode(200)
                .setObjectBody(responseBody)
                .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                .build();
    }
}

This example retrieves the query string parameters from the input object, which is passed as the first argument to the Lambda function. It then uses the get() method to retrieve the value of the name parameter and saves it to a variable. Then the function creates an instance of the Response class with the message “Hello, ” + name and returns it as the response to the request.

Aws Lambda Java Put Example code

Here is an example of an AWS Lambda function written in Java that handles an HTTP PUT request and returns a JSON response:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();
        try {
            // parse the put data
            JsonNode putData = objectMapper.readTree((String) input.get("body"));

            // do something with the data
            String name = putData.get("name").asText();
            Response responseBody = new Response("Hello, " + name);

            return ApiGatewayResponse.builder()
                    .setStatusCode(200)
                    .setObjectBody(responseBody)
                    .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                    .build();
        } catch (IOException e) {
            logger.log(e.getMessage());
            return ApiGatewayResponse.builder()
                    .setStatusCode(500)
                    .setObjectBody("Error while parsing input: " + e.getMessage())
                    .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                    .build();
        }
    }
}

In this example, the class MyLambdaFunction implements the RequestHandler interface, which is provided by the AWS Lambda

Aws Lambda Java Delete Example code

Here is an example of an AWS Lambda function written in Java that handles an HTTP DELETE request and returns a JSON response:

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

import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();

        // Retrieve query string parameters
        Map queryParams = (Map)input.get("queryStringParameters");

        // Retrieve id
        String id = queryParams.get("id");

        // Delete the item
        deleteItem(id);

        // Create a response
        Response responseBody = new Response("Successfully deleted item with id: " + id);

        return ApiGatewayResponse.builder()
                .setStatusCode(200)
                .setObjectBody(responseBody)
                .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                .build();
    }
}

This example retrieves the query string parameters from the input object, which is passed as the first argument to the Lambda function. It then uses the get() method to retrieve the value of the id parameter and saves it to a variable. It then calls the deleteItem(id) function to delete the item from the database. Finally, it creates an instance of the Response class with the message “Successfully deleted item with id: ” + id and returns it as the response to the request.

You would need to create a new Lambda function in the AWS Lambda console and then upload the JAR file containing this code. After that, you would need to configure an API Gateway trigger to handle the incoming DELETE request and route it to your Lambda function.

Aws Lambda Java Patch example code

Here is an example of an AWS Lambda function written in Java that handles an HTTP PATCH request and returns a JSON response:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();
        try {
            // parse the patch data
            JsonNode patchData = objectMapper.readTree((String) input.get("body"));

            // do something with the data
            String id = patchData.get("id").asText();
            String newValue = patchData.get("new_value").asText();
            updateItem(id, newValue);

            Response responseBody = new Response("Successfully updated

Amazon S3 and SpringBoot code example

What is Amazon S3?

Amazon S3 (Simple Storage Service) is an object storage service provided by Amazon Web Services (AWS). It allows you to store and retrieve data from anywhere on the web, making it a useful service for storing and accessing large amounts of data.

Objects in Amazon S3 are stored in buckets, which are containers for objects. Objects are stored as binary data, along with metadata that describes the object. The metadata includes information such as the object’s size, content type, and access control information.

Amazon S3 provides a range of storage classes that offer different levels of durability and availability. The storage classes include Standard, Standard-Infrequent Access (Standard-IA), and One Zone-Infrequent Access (One Zone-IA), as well as options for storing data in a specific region or for archival purposes.

Amazon S3 is a highly scalable, reliable, and secure service, making it a popular choice for storing and accessing data in the cloud. It is widely used for storing and serving static assets, such as images and documents, as well as for storing data for backup and disaster recovery purposes.

Aws S3 Commandline example

You can use the AWS command-line interface (CLI) to manage Amazon S3 from the command line.

To install the AWS CLI, follow the instructions in the AWS documentation: https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html.

Once the AWS CLI is installed, you can use it to perform various actions on Amazon S3. Here are a few examples:

1. List buckets
To list all of the buckets in your AWS account, use the aws s3 ls command:

aws s3 ls

This will list the names of all of the buckets in your account.

2. Create a bucket
To create a new bucket in S3, use the aws s3 mb command followed by the name of the bucket:

aws s3 mb s3://my-new-bucket

This will create a new bucket with the given name.

3. Upload an object
To upload an object to S3, use the aws s3 cp command followed by the path to the local file and the destination in S3:

aws s3 cp local/file/path s3://my-bucket/path/to/object/in/s3.txt

This will upload the local file to the specified path in the bucket.

4. Download an object
To download an object from S3, use the aws s3 cp command followed by the path to the object in S3 and the local destination:

aws s3 cp s3://my-bucket/path/to/object/in/s3.txt local/file/path

This will download the object from S3 to the specified local destination.

You can find more information about the AWS CLI and the various actions you can perform with it in the AWS documentation: https://aws.amazon.com/documentation/cli/.

SpringBoot Amazon S3 Put object

To store an object in Amazon S3 using Spring Boot, you can follow these steps:

1. Add the AWS SDK for Java to your project dependencies. You can do this by including the following dependency in your pom.xml file if you are using Maven:


    com.amazonaws
    aws-java-sdk-s3
    1.11.875

2. Create an AmazonS3 client using your AWS access key and secret key. You can find these in the AWS Management Console under “My Security Credentials”.

AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(credentials))
                    .withRegion(region)
                    .build();

3. Create an InputStream for the object you want to upload. This can be done using a FileInputStream if you want to upload a file from the local file system, or using any other method that returns an InputStream.

4. Use the putObject method of the AmazonS3 client to store the object in S3.

String bucketName = "my-s3-bucket";
String key = "path/to/object/in/s3.txt";
s3Client.putObject(bucketName, key, inputStream, new ObjectMetadata());

This will store the object with the given key in the specified bucket. The ObjectMetadata parameter allows you to set metadata for the object, such as content type and content encoding.

SpringBoot Amazon S3 Delete Object

To expose a REST API for deleting an object from Amazon S3 using Spring Boot, you can follow these steps:

1. Add the AWS SDK for Java to your project dependencies as described in the previous answer.

2. Create an AmazonS3 client using your AWS access key and secret key, as described in the previous answer.

3. Create a REST controller class with a method that accepts a request to delete an object from S3.

@RestController
public class S3Controller {

    @DeleteMapping("/s3/{bucketName}/{key}")
    public ResponseEntity deleteObject(@PathVariable String bucketName, @PathVariable String key) {
        // Delete object from S3
        s3Client.deleteObject(bucketName, key);
        return ResponseEntity.ok().build();
    }
}

This controller method will handle DELETE requests to the /s3/{bucketName}/{key} endpoint, where {bucketName} and {key} are path variables representing the name of the bucket and the key of the object to delete, respectively. The method will delete the object from S3 and return an HTTP 200 response.

SpringBoot Amazon S3 List Object example

To list the objects in a bucket in Amazon S3 using Spring Boot, you can use the listObjects method of the AmazonS3 client.

1. Add the AWS SDK for Java to your project dependencies as described in the previous answer.

2. Create an AmazonS3 client using your AWS access key and secret key, as described in the previous answer.

3. Use the listObjects method to retrieve a list of objects in the bucket.

String bucketName = "my-s3-bucket";
ObjectListing objectListing = s3Client.listObjects(bucketName);
List objectSummaries = objectListing.getObjectSummaries();
for (S3ObjectSummary objectSummary : objectSummaries) {
    System.out.println("Key: " + objectSummary.getKey());
    System.out.println("Size: " + objectSummary.getSize());
    System.out.println("Last modified: " + objectSummary.getLastModified());
}

This will retrieve a list of S3ObjectSummary objects, which contain information about the objects in the bucket, such as the key, size, and last modified date. You can then iterate through the list and print out the desired information.

You can use the listObjects method to retrieve a list of objects in a bucket, or a list of objects that match a specific prefix or delimiter. You can find more information about the listObjects method and its options in the AWS documentation: https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingJava.html.

You can also expose this functionality as a REST API using a Spring Boot REST controller, as described in the previous answer.

How to develop Angular 12 Service Example

The previous post, we had introduced Angular Components (Angular4 Component). And in the tutorial, JavaSampleApproach will continuously show you how to use Angular Services (Angular4 Services) to develop an Angular Application.

Related articles:
How to setup Angular IDE with Spring Tool Suite
Create a new Angular4 Component – Multiple Components Angular Application

Continue reading “How to develop Angular 12 Service Example”