HTTP Proxy using APIGateway with CDK
β’
3 min read
Last week at work I had to integrate an ALB with APIGateway as a proxy. While its pretty straight forward with Console, Unfortunately, it was not using CDK. This is due to my lack of complete knowledge, and their docs. Both suck π.
Letβs look at the code on how to integrate APIGateway with an URL
import * as cdk from "aws-cdk-lib";
import { Construct } from "constructs";
import { HttpIntegration, RestApi } from "aws-cdk-lib/aws-apigateway";
// import * as sqs from 'aws-cdk-lib/aws-sqs';
export class ApiGwHttpProxyStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// π π ALB URL
const albUrl = "http://example.com";
// π π first create a REST API Gateway
const restAPI = new RestApi(this, "httpProxyAPIGateway", {
restApiName: "httpProxyAPIGateway",
});
// π π https://docs.aws.amazon.com/apigateway/latest/developerguide/setup-http-integrations.html
const proxyIntegration = new HttpIntegration(`${albUrl}/{proxy}`, {
httpMethod: "ANY",
options: {
requestParameters: {
"integration.request.path.proxy": "method.request.path.proxy",
},
},
proxy: true,
});
// π π https://docs.aws.amazon.com/apigateway/latest/developerguide/setup-http-integrations.html
const proxyMethodOptions = {
requestParameters: {
"method.request.path.proxy": true,
},
};
// π π top level empty route
// for some reason API Gateway doesn't attach single `/` path so attaching it here
restAPI.root.addMethod(
"ANY",
new HttpIntegration(albUrl, {
httpMethod: "ANY",
}),
);
// this could be an empty resource too
const resource = restAPI.root.addResource(`some-resource`);
// proxy
resource
.addResource("{proxy+}")
.addMethod("ANY", proxyIntegration, proxyMethodOptions);
}
}
The above code deploys APIGateway and Integrates Proxy. Letβs deploy it with following command
cdk deploy
CDK outputs APIGateway URL as follows