Sai Umesh

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

image info image info image info


Sai Umesh

I’m Sai Umesh, a software engineer based in India. Working as a DevOps engineer.