Home > Software design >  Access path variable in AWS lambda
Access path variable in AWS lambda

Time:08-01

I have created REST API Gateway with path /{productId} And I have a simple Java handler:

public class UpdateProductHandler implements RequestHandler<ProductRequest, ProductResponse> {

    protected final Logger logger = Logger.getLogger(UpdateProductHandler.class.getName());

    @Override
    public ProductResponse handleRequest(ProductRequest productRequest, Context context) {

    }

}

The product request looks like this:

{
    "name": "name",
    "price": 51,
    "pictureUrl": "image.png"
}

How do I access the path variable in my handler? I saw a few answers that suggested making some kind of mapping in my Integration Request in the API gateway, to pass the path variable in the body. But it doesn't seem right, to do it. Is there any other way to achieve it?

When I was playing with HTTP API, my handler was accepting InputStream, inside which I had all information about requests. I like the REST API way when a ready object is already passed inside the handler, so maybe I can somehow access the path variable from context or something? Maybe I need to enable Use Lambda Proxy integration in my Integration Request?

CodePudding user response:

Check the answer below

How do I map path parameters from an API Gateway API to the Request Object of a Java Lambda

use the APIGatewayProxyRequestEvent instead of your own Java Object,

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;


/**
 * Handler for requests to Lambda function.
 */
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

    public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {

Map<String, String> pathParameters = input.getPathParameters();
    String id = pathParameters.get("id");
    String body = input.getBody(); 
    String path = input.getPath();

    
  • Related