Search⌘ K
AI Features

Response Integration

Explore how AWS API Gateway handles response integration to transform backend API responses using mapping templates and context variables. Learn to customize response headers, status codes, and bodies including integration with external APIs for enhanced functionality.

API response

A REST API request usually yields a response from the server. This response can be either a complete JSON, for instance, in response to a GET or a POST request, or a simple status code returned in response to some PUT request. When this data flows through the API Gateway, we have all the freedom to play with it. We can translate the headers and return codes and transform the body using the Velocity templates.

API Gateway provides request integration to transform the input request to the target API. Similarly, it enables response integration to translate the response of the target API to what the API client requires in the response.

The HTTP API and WebSocket API can be configured for response integration. They have minimal functionality, however. To use the full features, we should use the REST API.

Example

We can configure the response integration in the API Gateway in the CloudFormation template, as shown below.

export const handler = async (event, context) => {
  return event;
};
Response integration with Lambda function

Click "Run" to deploy and test the API. After deploying the new API, the script invokes this API that invokes the Lambda function in turn. The Lambda function echoes the input data. The Response Integration configured in the template.yml maps this into a larger JSON with additional information about the timestamp and IP address. Let’s look into this code to see how it works.

Check the lines 48-54 in template.yml. Here, we define the Response Integration. The responseTemplate is easy to read. It builds the response body using the $context.identity.sourceIp and $context.requestTime and $input.body.

The $input variable, as we can guess, is the input to the mapping template, that is, the output of the Lambda function invoked by the API Gateway. The $input.body presents this body of this input without any modification or parsing. API Gateway provides other constructs like $input.json() that parse the input as a JSON string and access the fields. API Gateway documentation provides a detailed reference for $input. The $context contains a chunk of information about the context of the API invocation. We can find the source IP address, request time, AWS account details, information about the authorization/authentication in place, and much more. We can check the details of the $context in the API Gateway documentation.

Mapping external API

The response mapping can be convenient when we integrate with an external API. Let’s check the IP Info API and build an API that enhances the free IP Info API to get the caller's address.

#!/bin/sh -v

# -----------------------------------------------------------------
# Configure the AWS CLI to let it communicate with your account
# -----------------------------------------------------------------
aws configure set aws_access_key_id $aws_access_key_id
aws configure set aws_secret_access_key $aws_secret_access_key
aws configure set region us-east-1

# -----------------------------------------------------------------
# Delete any old deployments
# -----------------------------------------------------------------
# 1. Trigger CloudFormation stack delete
# 2. Wait for the stack to be deleted 
aws cloudformation delete-stack --stack-name  EducativeCourseApiGateway
aws cloudformation wait stack-delete-complete --stack-name EducativeCourseApiGateway


# -----------------------------------------------------------------
# With everything ready, we initiate the CloudFormation deployment.
# -----------------------------------------------------------------
aws cloudformation deploy \
    --template-file template.yml \
    --stack-name EducativeCourseApiGateway \
    --capabilities CAPABILITY_NAMED_IAM \
    --parameter-overrides DeployId="$RAND" SourceCodeBucket="educative.${bucket}" \
    --region us-east-1

# -----------------------------------------------------------------
# Get the API ID of the Rest API we just created.
# -----------------------------------------------------------------
apiId=`aws cloudformation list-stack-resources --stack-name EducativeCourseApiGateway | jq -r ".StackResourceSummaries[1].PhysicalResourceId"`
echo "API ID: $apiId"

# -----------------------------------------------------------------
# This is the URL for the API we just created
# -----------------------------------------------------------------
url="https://${apiId}.execute-api.us-east-1.amazonaws.com/v1"
echo $url

# -----------------------------------------------------------------
# Invoke the URL to test the response
# -----------------------------------------------------------------
curl --location --request GET $url --header 'Content-Type: application/json'


Response integration with external API

Click "Run" to deploy and test the API. After deploying the new API, the script invokes this API that invokes the IP Info API that returns the details about the source IP. The Response Integration configured in template.yml extracts fields from this JSON to get the precise values required. Let’s see how this code works.

  • Lines 35 and 37 define the path parameter for the target API. The path variable {ip} comes from the $context.identity.sourceIp.

  • Line 42 defines the response mapping. This mapping works in two steps. The first line picks the JSON object from the input (the response of the target API). The second line builds the user address out of the fields in this JSON.

So, we get one API that returns the caller's geographical location. It’s made so easy by the API Gateway data mapping.

Web console

Let’s now check this out on the API Gateway console. Open the EducativeRestAPI and the GET method in the base resource. Check the Integration Response and expand it to see the Mapping Template.

Note a few points on the API Gateway console.

  • The endpoint URL points to the target API.

  • The URL path parameters include the source IP Address obtained from the API context.

  • The integration response contains a Velocity template that maps the specific fields from the target API response.