When using API Gateway with a backend such as ECS or EKS (via a load balancer), you don’t have direct access to requestContext in the same way that you do with Lambda. Instead, you can Extract fields from requestContext (such as authorizer.tenantId) and pass them as HTTP headers.
To ensure that the backend receives tenant information, you can configure integration request mapping to add details from the requestContext to HTTP headers. Mappings ara configured via a Mapping Template for the content type (usually application/json) that uses VTL lto add an element to the response body
{
"tenantId": "$context.authorizer.tenantId"
}or set an HTTP header:
#set($context.requestOverride.header["x-tenant-id"] = $context.authorizer.tenantId)When using an API Gateway in front an application load balancer, the result is typically achieved with a configuration on the API Gateway. First, an HttpIntegration needs to be configured
lb = elbv2.ApplicationLoadBalancer(self, "LB", vpc=vpc, internet_facing=True)
listener = lb.add_listener("PublicListener", port=80)
listener.add_targets("ECS", port=80, targets=[service])
# API Gateway Integration with Load Balancer
api = apigateway.RestApi(self, "MyApi",
rest_api_name="My Service",
description="API Gateway to ECS integration"
)
# Integration with ALB (backed by ECS Service)
alb_integration = apigateway.HttpIntegration(
url=f"http://{lb.load_balancer_dns_name}",
integration_http_method="ANY",
options=apigateway.IntegrationOptions(
request_parameters={
"integration.request.header.x-tenant-id": "context.authorizer.tenantId"
}
)then a resource can be created and when attaching a method, we can add mandatory request parameters
# Application Load Balancer
# Add resources and methods
items = api.root.add_resource("items")
items.add_method(
"GET",
integration=alb_integration,
# mandatory header
request_parameters={
"method.request.header.x-tenant-id": True
}
)