5
votes

We are using AWS CDK to create our Serverless REST API. However, there are a large number of endpoints and sometimes we have to destroy and redeploy our stack. To prevent the REST API URL from changing with each deployment, I am planning to create the API GATEWAY in one stack and add methods and resources in a separate stack. How can I refer the created rest API in a separate stack?

Tried to implement something from https://github.com/aws/aws-cdk/issues/3705, but all of the resources(API Gateway, resource and methods) are being pushed in a single stack instead of API Gateway in one stack and the resources in other stack.

Relevant codes snippets are provided below:

bts-app-cdk.ts

const first = new FirstStack(app, 'FirstStack', {
    env: {
        region: 'us-east-1',
        account: '1234567890',
    }
    });

const second = new SecondStack(app, 'SecondStack', {
    apiGateway: first.apiGateway,
    env: {
        region: 'us-east-1',
        account: '1234567890',
    }
});

second.addDependency(first)

first-stack.ts

export class FirstStack extends cdk.Stack {

    public readonly apiGateway: apig.IResource;

    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

        const apiGateway = new apig.RestApi(this, 'BooksAPI', {
            restApiName:'Books API',
        })
        apiGateway.root.addMethod('GET');

        this.apiGateway = apiGateway.root;
    }
}

second-stack

export interface SecondStackProps extends cdk.StackProps {
    readonly apiGateway: apig.IResource;
}

export class SecondStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props: SecondStackProps) {
        super(scope, id, props);

        props.apiGateway.addMethod('ANY')

    }
}
1

1 Answers

1
votes

Seems that there is no way at the moment except using Cfn constructs, here's the github issue to track https://github.com/aws/aws-cdk/issues/1477