How do I create a Lambda function to process custom headers of messages passed through an API created in the Amazon API Gateway?

By default, an AWS Lambda function only ingests the request body received by an API created in the Amazon API Gateway. The example in this article illustrates how to use the curl utility to send a message to the API Gateway, which uses a body mapping template to extract any custom headers added to the message. Then the API sends the updated message to a Lambda function to process the headers and return one or more header values from the original message.

Follow these steps to pass custom headers from an Amazon API Gateway API to a Lambda function.

Create the Lambda function

Note

The following example assumes that you have already configured the necessary permissions for AWS Lambda and the Amazon API Gateway as described at Authentication and Access Control for AWS Lambda and Set IAM Permissions to Access API Gateway. For purposes of this example you should create a test Role with the two managed Policies AmazonAPIGatewayInvokeFullAccess and AmazonAPIGatewayPushToCloudWatchLogs attached.

1.    Open the AWS Lambda console and choose Functions.

2.    Choose Create a Lambda function.

3.    Choose the option Configure function.

4.    Provide appropriate values for Name, Description, and Runtime. This example uses the name CustomHeaders. This example depends on the Node.js 4.3 runtime.

5.    Enter the following code for the Lambda function, and make sure that Edit code inline is selected for the Code entry type option.

exports.handler = (event, context) => {

context.done(null, "This message header was processed by Amazon " +event.headers["header1"]);

};

6.    Under Lambda function handler and role, choose Choose an existing role for Role, and select the name of the test role that you created earlier for Existing role. All remaining options on this page should be left at default values. Choose Next.

7.    Choose Create Function and select the Publish option from the Actions menu.

Create the API Gateway API

1.    Open the API Gateway console, choose APIs, and choose Create API to display the Create new API page. Verify that the New API option is selected. Specify the name SendtoLambda and a short description.

2.    Choose Create API.

3.    Add a resource to the API. From the left pane, choose Resources and from the Actions menu, choose Create Resource to display the New Child Resource page. Enter HeadersResource for Resource Name and then choose Create Resource.

4.    In the API Gateway console, select the new headersresource. From the Actions drop-down menu, choose Create Method and choose POST from the drop-down box that appears. Select the check mark displayed to the right of the POST method to display the /headersresource - POST - Setup page.

5.    On this page, verify that the Integration type is set to Lambda Function, select the appropriate Lambda Region, and enter the name CustomHeaders. Choose Save to display the Add Permission to Lambda Function dialog box, and choose OK.

6.    Select the POST method in the Resources pane to display the method’s execution details. Select the Integration Request link listed under the /headersresource - POST - Method Execution section.

7.    Keep the default settings for the Integration Request option and expand Body Mapping Templates. For Request body passthrough, choose the "When there are no templates defined (recommended)" option, and then choose Add mapping template to display the Content-Type option. Enter application/json under Content-type and select the checkmark.

8.    Enter the following code into the code input section. This code loops through the message headers and adds each header to the body of the response message.

{

    "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

    }

}

9.    Choose Save to update the POST method for the API.

10.    From the Actions menu, choose Deploy API, provide the name of a stage (such as prod, test, or beta). After you deploy the API, you will be redirected to the Stage Editor page.

11.    In the Stage Editor page, select the POST method and make a note of the URL displayed next to Invoke URL: at the top of the Stage Editor, through which you will invoke your method.

12.    Use the curl utility to send a message to the API Gateway. The following example 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\"}"

13.    You should see the following output displayed in the console:

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

Note: If you need to install curl on Windows, consider downloading Git for Windows which includes the GNU bash shell and other Linux tools such as curl, tail, cat, grep, gzip, and Perl.

Another useful testing tool is PostMan, available for free as a Chrome or Mac app.

In Summary

These steps provide an overview of this example:

1.    A message is sent to the POST method of an API Gateway resource configured with an integration request to a Lambda function.

2.    The integration request uses a body mapping template to copy message headers into the message body.

3.    The API Gateway resource sends an updated response to the Lambda function.

4.    The Lambda function returns the header from the original message to the caller.

Amazon API Gateway, AWS Lambda, body mapping template, Node.js, integration, custom headers, function, resource, stage, deploy, request body


Did this page help you? Yes | No

Back to the AWS Support Knowledge Center

Need help? Visit the AWS Support Center

Published: 2016-10-06