How to use AWS CDK to look up existing ApiGateway

Viewed 5152

I am using AWS CDK to build my lambda, and I would like to register endpoints from the lambda's CDK stack.

I found I can get an existing ApiGateway construct using fromRestApiId(scope, id, restApiId) (documentation here)

So currently this works well:

    //TODO how to look up by ARN instead of restApiId and rootResourceId??
    const lambdaApi = apiGateway.LambdaRestApi
                                .fromRestApiAttributes(this, generateConstructName("api-gateway"), {
                                    restApiId: <API_GATEWAY_ID>,
                                    rootResourceId: <API_GATEWAY_ROOT_RESOURCE_ID>,
                                });

    const lambdaApiIntegration = new apiGateway.LambdaIntegration(lambdaFunction,{
        proxy: true,
        allowTestInvoke: true,
    })

    const root = lambdaApi.root;

    root.resourceForPath("/v1/meeting/health")
        .addMethod("GET", lambdaApiIntegration);

But I would like to deploy to many AWS accounts, and many regions. I don't want to have to hardcode the API_GATEWAY_ID or API_GATEWAY_ROOT_RESOURCE_ID for each account-region pair.

Is there a more generic way to get the existing ApiGateway construct, (e.g. by name or ARN)?

Thank you in advance.

1 Answers

Lets take a simple Api with one resource

const restApi = new apigw.RestApi(this, "my-api", {
  restApiName: `my-api`,
});
const mockIntegration = new apigw.MockIntegration();
const someResource = new apigw.Resource(this, "new-resource", {
  parent: restApi.root,
  pathPart: "somePath",
  defaultIntegration: mockIntegration,
});
someResource.addMethod("GET", mockIntegration);

Lets assume we want use this api and resource in another stack, we first need to export

new cdk.CfnOutput(this, `my-api-export`, {
  exportName: `my-api-id`,
  value: restApi.restApiId,
});

new cdk.CfnOutput(this, `my-api-somepath-export`, {
  exportName: `my-api-somepath-resource-id`,
  value: someResource.resourceId,
});

Now we need to import in new stack

const restApi = apigw.RestApi.fromRestApiAttributes(this, "my-api", {
  restApiId: cdk.Fn.importValue(`my-api-id`),
  rootResourceId: cdk.Fn.importValue(`my-api-somepath-resource-id`),
});

and simply add additional resources and methods.

const mockIntegration = new apigw.MockIntegration();
new apigw.Resource(this, "new-resource", {
  parent: restApi.root,
  pathPart: "new",
  defaultIntegration: mockIntegration,
});
Related