AWS Code Sample
Catalog

The AWS Documentation website is getting a new look!
Try it now and let us know what you think. Switch to the new look >>

You can return to the original look by selecting English in the language selector above.

widget_service.ts

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

// Copyright 2010-2019 Amazon.com, 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 // // http://aws.amazon.com/apache2.0/ // // 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 core = require("@aws-cdk/core"); 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 core.Construct { constructor(scope: core.Construct, id: string) { super(scope, id); const bucket = new s3.Bucket(this, "WidgetStore"); const handler = new lambda.Function(this, "WidgetHandler", { runtime: lambda.Runtime.NODEJS_8_10, // So we can use async in widget.js code: lambda.Code.asset("resources"), handler: "widgets.main", environment: { BUCKET: bucket.bucketName } }); bucket.grantReadWrite(handler); // was: 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-7-11

Author: Doug-AWS

Type: full-example

On this page: