How do I pass custom headers through API Gateway to a Lambda function using custom Lambda integration?

Last updated: 2020-01-08

How do I create an AWS Lambda function to process custom headers of messages passed through an Amazon API Gateway API?

Short Description

By default, a Lambda function only ingests the request body received by an API Gateway API. To pass custom headers from an API Gateway API to a Lambda function, use curl to send a message to the API using a body mapping template to extract any custom headers added to the message.

The API sends the updated message to a Lambda function to process the headers, returning one or more header values from the original message.

Resolution

Configure IAM permissions

Configure the required AWS Identity and Access Management (IAM) permissions for Lambda and API Gateway. For more information, see Control Access to an API with IAM Permissions.

For testing, create an IAM role and attach the AWS managed policies AmazonAPIGatewayInvokeFullAccess and AmazonAPIGatewayPushToCloudWatchLogs.

Create a Lambda function

1.    Open the Lambda console.

2.    If you're new to Lambda, choose Get Started Now. If not, choose Create function. The Create function page opens to the Author from scratch option.

3.    With Author from scratch selected, under Basic information, do the following:
For Function name, enter a name, such as CustomHeaders.
For Runtime, choose Node.js 12.x.

4.    Under Permissions, expand Choose or create an execution role.

5.    Choose Use an existing role.

6.    For Existing role, choose the execution role that you created earlier.

7.    Choose Create function.

8.    On the Configuration pane, under Function code, replace the code in the editor pane (index.js) with the following example function code:

exports.handler = (event, context, callback) => {
// TODO implement
callback(null, "This message header was processed by Amazon " +event.headers["header1"]);
};

9.    Choose Save.

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

Create an API Gateway API

1.    Open the API Gateway console.

2.    If you have any existing APIs in the console, choose Create API. If not, continue to the next step.

3.    For Choose an API type, under REST API, choose Build.

4.    Under Create new API, choose New API.

5.    Under Settings, do the following:
Enter an API name, such as SendtoLambda.
(Optional) Enter a Description.
Leave Endpoint Type as Regional.

6.    Choose Create API.

Configure the API

1.    In the API Gateway console, in the Resources pane of your new API, choose Actions, and then choose Create Resource.

2.    In the New Child Resource pane, do the following:
Enter a Resource Name, such as HeadersResource.
Choose Create Resource.

3.    Choose Actions, and then choose Create Method.

4.    From the dropdown menu under /headersresource, choose POST, and then choose the check mark icon.

5.    In the / headersresource - POST - Setup pane, do the following to configure your integration point:
For Integration type, choose Lambda Function.
For Lambda Region, choose the AWS Region of your Lambda function.
For Lambda Function, enter the name of your Lambda function.
Choose Save.

6.    In the Add Permission to Lambda Function dialog, choose OK.

7.    In the /headersresource - POST - Method Execution pane, choose Integration Request.

8.    In the /headersresource - POST - Integration Request pane, do the following:
Expand Mapping Templates.
For Request body passthrough, choose When there are no templates defined (recommended).
Choose Add mapping template.
For Content-Type, enter application/json, and then choose the check mark icon (Create).

9.    In the mapping template 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

1.    In the API Gateway console, in the Resources pane of your API, choose Actions, and then choose Deploy API.

2.    In the Deploy API dialog, do the following:
For Deployment stage, choose [New Stage].
For Stage name, enter a name, such as test.
(Optional) Enter a Stage description and Deployment description.
Choose Deploy.

3.    In the Stage Editor pane, copy the Invoke URL to your clipboard. The URL looks like this: https://1a2bc3d456.execute-api.region.amazonaws.com/test.

Test your API

Use curl to send a message to your API Gateway API. For more information about curl, see the cURL project website.

Tip: To install curl on Windows, you can download Git for Windows, which includes the GNU Bash shell and other Linux tools, such as curl, tail, cat, grep, gzip, and Perl. To download Git for Windows, see Downloads on the Git website. For more information about Bash, see GNU Bash on the GNU website.

This example command returns the value of the header1 header referenced by the Lambda function:

curl -H "Content-Type: application/json" -H "header1: API Gateway and AWS Lambda" -X POST -d "{\"API_body\": \"This is the body\"}" https://restApiId.execute-api.region.amazonaws.com/stageName/headersresource

Note: Replace https://restApiId.execute-api.region.amazonaws.com/stageName in the command with the invoke URL for your API.

If successful, you see the following output:

"This message header was processed by Amazon API Gateway and AWS Lambda"