3

How can I request the used HTTP Method in an AWS Lambda handler in JAVA? There is a argument 'context', but after a look on it, I can't request the used HTTP method.

HTTP-Methods are: GET, POST, PUT

BTW: Here is the answer for javascript: How to get the HTTP method in AWS Lambda?

best regards, lars

Community
  • 1
  • 1
Lars Wi
  • 71
  • 1
  • 9
  • 1
    That answer for JavaScript will work just as well for Java. You have to map the HTTP method to a context field in your API Gateway mapping template, as described in that answer. – Mark B Jan 11 '17 at 15:20
  • thanks to you mark! I mapped the 'http-method' context field. But how can i access this information from java? In javascript its no problem to extend objects as described in the other stackoverflow post. – Lars Wi Jan 11 '17 at 15:50
  • I don't really use Java in AWS Lambda, but it looks like you will have to map any custom properties in your API Gateway mapping template to the event object since you can't extend the Context object in Java. – Mark B Jan 11 '17 at 15:54
  • okay. But we're using custom objects as our first argument in the handler. But since we just started with developing with AWS lambda...maybe we shoud switch to javascript ;) – Lars Wi Jan 11 '17 at 16:02

1 Answers1

2

You have several options on how you could receive the httpMethod in Java. One of the easiest would be to rename 'http-method' to 'httpMethod' in your Integration Request in API Gateway and then use the RequestHandler Interface for your Lambda handler which will marshal your JSON directly to a Java Object:

package example;

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

public class Hello implements RequestHandler<PojoRequest, PojoResponse> {

    public PojoResponse handleRequest(PojoRequest request, Context context) {
        System.out.println(String.format("HTTP method is %s.", request.getHttpMethod()));
        return new PojoResponse();
    }
}

Then you can create whatever Pojo you want to be the request, for example:

package example;

public class PojoRequest {
    private String firstName;
    private String lastName;
    private String httpMethod;

    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 String getHttpMethod() {
        return httpMethod;
    }

    public void setHttpMethod(String httpMethod) {
        this.httpMethod = httpMethod;
    }
}

See: http://docs.aws.amazon.com/lambda/latest/dg/java-handler-using-predefined-interfaces.html

Dave Maple
  • 8,102
  • 4
  • 45
  • 64
  • Thanks Dave for this workaround. But I won't http information in my entity objects. Is there no other option? – Lars Wi Jan 12 '17 at 08:09