AWS: API-Gateway – convert to binary

After creating a resource and a GET method, fill in the ‘Integration Response’ part for response 200.

aws-api-gateway-convert-to-binary

Now, all we need to to is make our lambda to return the data in ‘encodede’ way:

 
public class AmazonS3Wrapper {

    private static final Logger log = LogManager.getLogger(AmazonS3Wrapper.class);

    private AmazonS3 amazonS3;

    public AmazonS3Wrapper(AmazonS3 amazonS3) {
        this.amazonS3 = amazonS3;
    }

    public Try<Void> getBytes(String bucket, String key, OutputStream os) {
        log.info("Loading data from: " + bucket + "/" + key);
        try (InputStream s3is = amazonS3.getObject(bucket, key).getObjectContent();
             OutputStream os64 = Base64.getEncoder().wrap(os)) {
            byte[] buf = new byte[8192];
            int bytesRead;
            while ((bytesRead = s3is.read(buf)) != -1) {
                os64.write(buf, 0, bytesRead);
            }
        } catch (IOException e) {
            return Try.failure(e);
        }
        return Try.success(null);
    }
}

And run the code in main handler method:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.InputStream;
import java.io.OutputStream;

@SuppressWarnings("unused")
public class Lambda implements RequestStreamHandler {

    private static final Logger log = LogManager.getLogger(Lambda.class);

    @Override
    public void handleRequest(InputStream is, OutputStream os, Context context) {
        log.info("Triggered lambda");

        final AmazonS3Wrapper amazonS3Wrapper = new AmazonS3Wrapper(amazonS3);
        amazonS3Wrapper.getBytes(bucket, key, os);

        log.info("Lambda finished.");
    }

}
Advertisements