amazon-web-servicesaws-api-gatewayaws-cdkaws-cdk-typescript

Nested JSON object from StepFunctions as API Gateway response in CDK


I am trying to grab a nested object from a step functions state machine output to return it as the body in the API GW response.

The output from the state machine looks like this although it seems to become an escaped string when it gets to the API Gateway (which is why I call $util.parseJson(...)):

{
  "statusCode": 200,
  "prop2": {
             "message": "Hello"
           }
}

What I want to return as the response body is prop2 like this:

{
  "message": "Hello"
}

The integration between the API GW and State machine looks like this (Typescript CDK):

// For context just in case
const api = new RestApi(...);
const apiResource= api.root.addResource("sample");

// What actually matters
apiResource.addMethod("POST", StepFunctionsIntegration.startExecution(createData, {
      integrationResponses: [
        {
          selectionPattern: "200",
          statusCode: "200",
          responseTemplates: {
            "application/json": [
              "#set($response = $util.parseJson($input.json(\"$.output\")))",
              "$response.prop2",
            ].join("\n"),
          }
        }
      ]
}));

However, this results in an empty response body. I have tried $response[\"prop2\"] but that seems fail and produce an internal server error.

Note that using just $response does return the State Machine output in JSON format.

Is this case posible? Or does API GW's VTL restrict it?


Solution

  • Apparently I had to stringify the response so that $util.parseJson(...) would properly process my payload.

    From my lambda:

    return {
        statusCode: 200,
        prop2: JSON.stringify(myObject),
    };