Lambda S3 Asset + API Gateway with the AWS CDK

1import * as cdk from "@aws-cdk/core";
2import * as lambda from "@aws-cdk/aws-lambda";
3import * as assets from "@aws-cdk/aws-s3-assets";
4import * as apigw from "@aws-cdk/aws-apigateway";
5import * as path from "path";
6
7export class HelloLambdaFromS3Stack extends cdk.Stack {
8 constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
9 super(scope, id, props);
10
11 // The following JavaScript example defines an directory
12 // asset which is archived as a .zip file and uploaded to
13 // S3 during deployment.
14 // See https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-assets-readme.html
15 const myLambdaAsset = new assets.Asset(
16 // @ts-ignore - this expects Construct not cdk.Construct :thinking:
17 this,
18 `HelloLambdaAssetsZip`,
19 {
20 path: path.join(__dirname, "../functions/hello-dynamo-zip"),
21 }
22 );
23
24 const fn = new lambda.Function(this, `HelloLambdaAssetFn`, {
25 code: lambda.Code.fromBucket(
26 // @ts-ignore
27 myLambdaAsset.bucket,
28 myLambdaAsset.s3ObjectKey
29 ),
30 timeout: cdk.Duration.seconds(300),
31 runtime: lambda.Runtime.NODEJS_12_X,
32 handler: "index.handler",
33 });
34
35 // API Gateway
36 const api = new apigw.RestApi(this, "myapi", {});
37 const helloWorldLambdaIntegration = new apigw.LambdaIntegration(fn);
38 const helloResource = api.root.addResource("hello");
39 helloResource.addMethod("GET", helloWorldLambdaIntegration);
40
41 // required for local dev
42 new cdk.CfnOutput(this, "Endpoint", {
43 value: `http://localhost:4566/restapis/${api.restApiId}/prod/_user_request_${helloResource.path}`,
44 });
45 }
46}