Search code examples
amazon-web-servicesaws-cliaws-cdk

Can I create resources and methods in AWS API Gatway using CDK or CLI?


Currently, I'm learning AWS CDK and I want to create an Api gateway with multiple resources and each with its own methods.

Can I do so using CDK or CLI or do I have to do so from the AWS web console?


Solution

  • Yes its possible from both, here is an example Lambda function with Rest API in CDK:

        const transactionFunction = new lambda.Function(this, 'TransactionFunction', {
          runtime: lambda.Runtime.NODEJS_14_X,
          memorySize: 1024,
          timeout: Duration.seconds(10),
          handler: 'index.handler',
          code: lambda.Code.fromAsset(path.join(__dirname, '../src/lambda/transaction/')),
          environment: {
            REGION: Stack.of(this).region
          }
        });
    
        const api = new RestApi(this, 'TransactionAPI', {
          description: 'Transactions API',
          deployOptions: {
            stageName: 'dev'
          },
          defaultCorsPreflightOptions: {
            allowHeaders: [
              'Content-Type',
              'X-Amz-Date',
              'Authorization',
              'X-Api-Key',
            ],
            allowMethods: ['OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
            allowCredentials: true,
            allowOrigins: Cors.ALL_ORIGINS
          }
        })
    
        const transactions = api.root.addResource('transactions');
    
        transactions.addMethod('POST', new LambdaIntegration(transactionFunction));
    
        new CfnOutput(this, 'apiUrl', { value: api.url });
    

    https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway-readme.html#defining-apis