AWS Code Sample


Creates an S3 bucket, handler for HTTP requests, and API Gateway to Lambda functions.

// Copyright 2010-2019, Inc. or its affiliates. All Rights Reserved. // // This file is licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. A copy of the // License is located at // // // // This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. import cdk = require('@aws-cdk/cdk'); import apigateway = require('@aws-cdk/aws-apigateway'); import lambda = require('@aws-cdk/aws-lambda'); import s3 = require('@aws-cdk/aws-s3'); export class WidgetService extends cdk.Construct { constructor(scope: cdk.Construct, id: string) { super(scope, id); const bucket = new s3.Bucket(this, 'WidgetStore'); const handler = new lambda.Function(this, 'WidgetHandler', { runtime: lambda.Runtime.NodeJS810, // So we can use async in widget.js code:'resources'), handler: 'widgets.main', environment: { BUCKET: bucket.bucketName } }); bucket.grantReadWrite(handler.role); const api = new apigateway.RestApi(this, 'widgets-api', { restApiName: 'Widget Service', description: 'This service serves widgets.' }); const getWidgetsIntegration = new apigateway.LambdaIntegration(handler, { requestTemplates: { "application/json": '{ "statusCode": "200" }' } }); api.root.addMethod('GET', getWidgetsIntegration); // GET / const widget = api.root.addResource('{id}'); // Add new widget to bucket with: POST /{id} const postWidgetIntegration = new apigateway.LambdaIntegration(handler); // Get a specific widget from bucket with: GET /{id} const getWidgetIntegration = new apigateway.LambdaIntegration(handler); // Remove a specific widget from the bucket with: DELETE /{id} const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); widget.addMethod('POST', postWidgetIntegration); // POST /{id} widget.addMethod('GET', getWidgetIntegration); // GET /{id} widget.addMethod('DELETE', deleteWidgetIntegration); // DELETE /{id} } }

Sample Details

Service: cdk

Last tested: 2019-2-8

Author: Doug-AWS

Type: full-example

On this page: