How do I pass custom headers through API Gateway to a Lambda function with Lambda custom (non-proxy) integration?

5 minute read
0

I want to configure an AWS Lambda function through custom (non-proxy) integration to process custom headers that are passed through my Amazon API Gateway API.

Short description

By default, a Lambda function processes only the method request body that it receives from an API Gateway API request. To pass custom headers from an API Gateway API to a Lambda function, use a body mapping template. The API first sends the updated API request to a Lambda function to process the headers. Then, the Lambda function returns one or more header values from the original API request.

Resolution

Configure the required IAM permissions

Follow the instructions in Control access to a REST API with IAM permissions.

To test this procedure, create an AWS Identity and Access Management (IAM) role, and then attach the AmazonAPIGatewayInvokeFullAccess and AmazonAPIGatewayPushToCloudWatchLogs AWS managed policies. For more information, see AWS managed policies.

Create a Lambda function to handle custom headers from your API Gateway API

Complete the following steps:

  1. Open the Lambda console.
  2. Choose Create function. The Create function page opens with the Author from scratch option selected.
  3. In the Basic information pane, take the following actions:
    For Function name, enter a name that describes your function's purpose. For example: CustomHeaders.
    For Runtime, choose Node.js 20.x.
  4. Under Permissions, expand Change default execution role.
  5. Choose Use an existing role. A dropdown list of existing roles appears.
  6. For Existing role, choose the Lambda execution role that you created previously.
  7. Choose Create function.
  8. On the Code source pane, replace the index.mjs code in the editor pane with the following code:
    export const handler = async (event, context, callback) => {
      callback(null, "The custom header " +event.headers["header1"] +" has been processed successfully by AWS Lambda via Amazon API Gateway");
    };
    Choose Deploy.

For more information, see Building Lambda functions with Node.js.

Create an API Gateway REST API

Complete the following steps:

  1. Open the API Gateway console.
  2. Choose Create API.
    -or-
    If this is your first time using API Gateway, then a page that introduces you to the features of API Gateway appears. Under REST API, choose Build.
  3. In the Create REST API section, choose New API under API details.
  4. For API name, enter a name that describes your API's purpose. For example: SendtoLambda.
    (Optional) For Description, enter a short description of your API's purpose.
    For Endpoint Type, choose Regional.
  5. Choose Create API.

Configure your API's integration point and body mapping template

Complete the following steps:

  1. Open the API Gateway console.

  2. Choose the name of the API that you created previously. Your API's Resources page opens.

  3. On the Resources page, choose Create Resource.

  4. In the Create Resource pane, take the following actions:
    For Resource Name, enter a name that describes the resource. For example: HeadersResource.
    Choose Create Resource.

  5. Choose the Resource that you created, and then choose Create Method.

  6. In the Create Method pane, take the following actions:
    For method type, choose POST from the dropdown list.
    For Integration type, choose Lambda Function.
    Confirm that the Lambda proxy integration is disabled.
    For Lambda function, choose the AWS Region that hosts your function, and then enter the Lambda function's name or Amazon Resource Name (ARN).
    Choose Create method. This action automatically grants API Gateway permission to invoke your Lambda function.

  7. Choose POST for the resource method that you created in the previous step. Then, in the Method Execution pane, choose Integration Request.

  8. In the Integration Request pane, choose Edit and then take the following actions:
    For Request body passthrough, choose When there are no templates defined (recommended).
    Expand Mapping Templates at the bottom of the pane.
    Choose Add mapping template.
    For Content-Type, enter application/json.

  9. In the Template body editor, enter the following:

    {
      "method": "$context.httpMethod",
      "body" : $input.json('$'),
      "headers": {
        #foreach($param in $input.params().header.keySet())
        "$param": "$util.escapeJavaScript($input.params().header.get($param))"
        #if($foreach.hasNext),#end
        #end
      }
    }
  10. Choose Save.

Deploy your API to a new stage

Complete the following steps:

  1. Follow the instructions to deploy a REST API to a stage. For more information, see Set up a stage for a REST API in API Gateway.
  2. Choose the Deploy API button.
  3. In the Deploy API pop-up window, enter a new name for the stage, and then choose Deploy.
  4. Expand the stage on the Stages pane to view your resource and method that you created in the previous steps.
  5. Choose POST for your resource method and copy the Invoke URL to your clipboard.

REST API Invoke URL example

https://1a2bc3d456.execute-api.region.amazonaws.com/stageName/resourceName

Test your setup

To confirm that your API and Lambda function are processing headers, run the following curl command:

curl -H "Content-Type: application/json" -H "header1: value1" -X POST -d "{\"API_body\": \"This is the body\"}" https://restApiId.execute-api.region.amazonaws.com/stageName/resourceName

Note: Replace https://restApiId.execute-api.region.amazonaws.com/stageName/resourceName with your API's invoke URL.

Example output

"The custom header value1 has been processed successfully by AWS Lambda via Amazon API Gateway"

Note: To install curl on Windows, see Downloads on the Git website. For more information about curl, see the curl project website.

Related information

Set up data transformations in API Gateway

Managing permissions in AWS Lambda

Control access to a REST API with IAM permissions

AWS OFFICIAL
AWS OFFICIALUpdated 5 months ago