Search code examples
amazon-web-servicesaws-api-gatewayamazon-cloudfrontaws-cdk

Migrate from apigateway to apigatewayv2


How to migrate from apigateway to apigatewayv2 using AWS-CDK?

Specifically: I am using LambdaRestApi and restApiId and deploymentStage from that resource.

    // old
    const apiGw = new apigateway.LambdaRestApi(this, 'MyAPI', {
      handler: lambdaFrontend,
      proxy: true,
      binaryMediaTypes: ['*/*'],
    });

    // new
    const apiGw2 = new apigateway.CfnApi(this as any, 'MyAPIV2', {
      protocolType: "http",
      target: lambdaFrontend.functionArn,
    })

I am trying to get the OriginSource for CF like so: const domainName = ${apiGw.restApiId}.execute-api.${this.region}.${this.urlSuffix};

First question: How can I retrieve the domainName with ApiGW2?

I also need the stageName. Currently I am retrieving it like so: const originPath = '/' + apiGw.deploymentStage.stageName;

Second question: How can I retrieve the origin Path with ApiGW2?

Alternatively: Is there a better way to connect my ApiGW2 with CF?

    const fecf = new cf.CloudFrontWebDistribution(this, "MyCF", {
      originConfigs: [{
        customOriginSource: {
          domainName: `${apiGw.restApiId}.execute-api.${this.region}.${this.urlSuffix}`,
        },
        originPath: '/' + apiGw.deploymentStage.stageName,
      ...
   }

Solution

  • This can now be solved quite easily since we have official documentation for this now. If anybody out there wants to migrate to V2 now, this is the way:

        const httpApiIntegration = new apigatewayv2Integrations.LambdaProxyIntegration({
          handler: fn,
        });
        const httpApi = new apigatewayv2.HttpApi(this, "MyApiV2");
        httpApi.addRoutes({
          path: "/",
          methods: [HttpMethod.ANY],
          integration: httpApiIntegration,
        });
    
        new cloudfront.CloudFrontWebDistribution(this, "MyCf", {
          defaultRootObject: "/",
          originConfigs: [
            {
              customOriginSource: {
                domainName: `${httpApi.httpApiId}.execute-api.${this.region}.${this.urlSuffix}`,
              },
              behaviors: [
                {
                  isDefaultBehavior: true,
                },
              ],
            },
          ],
          enableIpV6: true,
        });
    

    https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigatewayv2-readme.html

    Steps:

    • create an integration (e.g. a lambda function), this comes from a dedicated package (apigatewayv2-integrations)
    • create an HttpApi, no options needed
    • New: Opposed to APIGWv1 you will have to add route handlers for your paths (httpApi.addRoutes).
    • Cloudfront config is very similar