├── .gitignore ├── Gruntfile.js ├── LICENSE ├── README.md ├── TODO.md ├── cloudformation ├── complete-api.template └── sample-params.json ├── index.js └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | cloudformation/api-params.json 2 | node_modules 3 | dist 4 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2016 Jeremy Thomerson 3 | * Licensed under the MIT license. 4 | */ 5 | 6 | 'use strict'; 7 | 8 | module.exports = function(grunt) { 9 | 10 | var pkg = grunt.file.readJSON('package.json'), 11 | zipName = grunt.option('zip-name') || (pkg.name + '.zip'), 12 | config; 13 | 14 | config = { 15 | zip: { 16 | include: [ 'index.js', 'src/**/*', 'node_modules/**/*' ], 17 | dest: 'dist/' + zipName, 18 | }, 19 | }; 20 | 21 | grunt.initConfig({ 22 | 23 | pkg: pkg, 24 | config: config, 25 | 26 | zip: { 27 | '<%= config.zip.dest %>': [ '<%= config.zip.include %>' ], 28 | }, 29 | 30 | }); 31 | 32 | grunt.loadNpmTasks('grunt-zip'); 33 | 34 | grunt.registerTask('default', [ 'zip' ]); 35 | 36 | }; 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2016 Jeremy Thomerson 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of 5 | this software and associated documentation files (the "Software"), to deal in 6 | the Software without restriction, including without limitation the rights to 7 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 8 | of the Software, and to permit persons to whom the Software is furnished to do 9 | so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CloudFormation Example for API Gateway With Lambda and DynamoDB 2 | 3 | ## What? 4 | 5 | This template tries to demonstrate a complete microservice that uses AWS 6 | services to create a simple serverless API. It uses CloudFormation to create 7 | the following and relate all of them to one another as needed: 8 | 9 | * API Gateway 10 | * API Resource (one) 11 | * API Methods (GET / POST) 12 | * Lambda Function 13 | * This is what implements the logic for the service, and the code for the function is also part of this repo. 14 | * DynamoDB Table 15 | * Configured to be used by the Lambda function. 16 | * IAM Roles and Policies 17 | * So that the API can invoke the function and the function has access to necessary resources. 18 | 19 | 20 | 21 | ## Why? 22 | 23 | Because it can be really tough getting all of this set up on your own. There 24 | are a number of examples of individual pieces, but I couldn't find examples of 25 | how to wire all of them together. 26 | 27 | The goal of this repo is that you can have a single repo that contains the 28 | Lambda code for the service, as well as the configuration for provisioning the 29 | service. The hope is that you could add automated unit testing, and if that 30 | passed, the same repo could build your dev environment, potentially run 31 | integration tests, and then either automatically or manually deploy the API. 32 | Automating all of this will greatly simplify things if your desire is to build 33 | self-contained serverless microservices. 34 | 35 | 36 | ## How to Use It 37 | 38 | 1. Install custom resources for API creation via CloudFront 39 | * We use Carl Nordenfelt's great [custom resources](https://github.com/carlnordenfelt/aws-api-gateway-for-cloudformation/) for making the API resources in AWS CloudFormation since CFN doesn't actually support them natively yet. To get started with it, please install them as described in his documentation: https://apigatewaycloudformation.bynordenfelt.com/. I built this using the latest version at the time: 1.5.0 (2016-04-10). 40 | 2. Copy `cloudformation/sample-params.json` to `cloudformation/api-params.json`. 41 | 3. Edit `cloudformation/api-params.json` to fill in your own values. 42 | 4. Run the following command: 43 | 44 | ``` 45 | aws cloudformation create-stack --stack-name \ 46 | --template-body file://./cloudformation/complete-api.template \ 47 | --parameters=file://./cloudformation/api-params.json \ 48 | --capabilities CAPABILITY_IAM 49 | ``` 50 | 51 | If you want to monitor the status of your stack creation on the CLI, you can use this command: 52 | 53 | ``` 54 | aws cloudformation describe-stacks --query='Stacks[*].{ Name: StackName, Status: StackStatus }' 55 | ``` 56 | 57 | 58 | ## License 59 | 60 | This software is released under the MIT license. See [the license file](LICENSE) for more details. 61 | 62 | Feel free to take the template and modify it for your own use. 63 | 64 | 65 | ## Contributing 66 | 67 | At this point I don't have my normal [jshint](http://jshint.com/), 68 | [jscs](http://jscs.info/), [Travis CI](https://travis-ci.org/) stack integrated 69 | in this repo. I also don't have unit testing - something I hope to add in the 70 | future. So, I don't have a way you can automatically validate your 71 | contributions. That said, if you want to contribute, please submit a pull 72 | request, but only after doing the following: 73 | 74 | 1. Make sure your code follows the coding standards that are in the file(s) you are editing (e.g. three space indentation, never a tab, never trailing whitespace). 75 | 2. (Obviously) Run your code and make sure that you can actually build a working stack with it. 76 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | # TODO 2 | 3 | ## Lock Down Lamba Invocation Permissions More 4 | 5 | Need to edit the `LambdaInvokePermission` to add `SourceArn` that points to the 6 | APIMethod, so that only the APIMethod can invoke it. 7 | 8 | 9 | ## Add Logging to API Deployment 10 | 11 | Logging can be enabled on the API deployment as shown in the example below. 12 | However, to do that some CloudWatch configuration must be done. There's an 13 | error about logging if you just add what's below. 14 | 15 | ``` 16 | "DeployAPI": { 17 | ... 18 | "methodSettings": { 19 | "*/*/metrics/enabled": true, 20 | "*/*/logging/loglevel": "ERROR" 21 | }, 22 | ... 23 | }, 24 | ``` 25 | 26 | ## Improve Grunt Build 27 | 28 | * Creating the Lambda zip: 29 | * Right now the grunt zip just zips everything - including all node_modules, even though none of them are needed. That needs to be improved. 30 | * Naming the zip 31 | * Need to figure out some way to avoid tight coupling so that the name of the zip used in the CFN template (parameters) is also used for the Grunt build. 32 | * Also need to figure out naming that allows for versioning. 33 | * Uploading the zip, etc 34 | -------------------------------------------------------------------------------- /cloudformation/complete-api.template: -------------------------------------------------------------------------------- 1 | { 2 | "AWSTemplateFormatVersion": "2010-09-09", 3 | 4 | "Description": "Creates an API gateway that's backed by a Lambda function", 5 | 6 | "Parameters": { 7 | "APIName": { 8 | "Description": "Name of the API to create", 9 | "Type": "String", 10 | "AllowedPattern": "[A-Za-z0-9]*", 11 | "MinLength": "4", 12 | "MaxLength": "2048", 13 | "ConstraintDescription": "must contain only alphanumeric characters (at least four)" 14 | }, 15 | "APIDescription": { 16 | "Description": "Description of the API to create", 17 | "Type": "String", 18 | "Default": "No description provided. Provide 'APIDescription' param to override this." 19 | }, 20 | "APIPath": { 21 | "Description": "URL path for the API", 22 | "Type": "String", 23 | "Default": "api", 24 | "AllowedPattern": "[A-Za-z0-9]*", 25 | "MinLength": "1", 26 | "MaxLength": "64", 27 | "ConstraintDescription": "must contain only alphanumeric characters (1-64 chars)" 28 | }, 29 | "APIStageName": { 30 | "Description": "Stage name to deploy the API to", 31 | "Type": "String", 32 | "Default": "dev", 33 | "AllowedPattern": "[A-Za-z0-9]*", 34 | "MinLength": "1", 35 | "MaxLength": "64", 36 | "ConstraintDescription": "must contain only alphanumeric characters (1-64 chars)" 37 | }, 38 | "LambdaCodeBucket": { 39 | "Description": "Name of the S3 bucket that's storing the Lamba function's zip file", 40 | "Type": "String" 41 | }, 42 | "LambdaCodePath": { 43 | "Description": "Path to the zip file of code for the Lambda function", 44 | "Type": "String" 45 | }, 46 | "APIGatewayCustomResourceARN": { 47 | "Description": "The ARN pointing to the Lambda function that creates custom API gateway resources (install from https://apigatewaycloudformation.bynordenfelt.com/). Example: arn:aws:lambda:us-east-1:123456789012:function:APIGatewayCustomResource-LambdaFunction-ABCDEFG123", 48 | "Type": "String" 49 | }, 50 | "DynamoReadCapacityUnits": { 51 | "Description": "Provisioned read throughput", 52 | "Type": "Number", 53 | "Default": "1", 54 | "MinValue": "1", 55 | "MaxValue": "10000", 56 | "ConstraintDescription": "must be between 1 and 10000" 57 | }, 58 | "DynamoWriteCapacityUnits": { 59 | "Description": "Provisioned write throughput", 60 | "Type": "Number", 61 | "Default": "1", 62 | "MinValue": "1", 63 | "MaxValue": "10000", 64 | "ConstraintDescription": "must be between 1 and 10000" 65 | } 66 | }, 67 | 68 | "Resources": { 69 | "BackingLambdaFunction": { 70 | "Type": "AWS::Lambda::Function", 71 | "Properties": { 72 | "Code": { 73 | "S3Bucket": { "Ref": "LambdaCodeBucket" }, 74 | "S3Key": { "Ref": "LambdaCodePath" } 75 | }, 76 | "FunctionName": { "Fn::Join": [ "-", [ { "Ref": "AWS::StackName" }, { "Ref": "APIName" } ] ] }, 77 | "Handler": "index.handler", 78 | "MemorySize": "128", 79 | "Role": { "Fn::GetAtt": [ "BackingLambdaExecutionRole", "Arn" ] }, 80 | "Runtime": "nodejs4.3", 81 | "Timeout": "3" 82 | } 83 | }, 84 | "BackingLambdaInvokePermission": { 85 | "Type": "AWS::Lambda::Permission", 86 | "Properties": { 87 | "FunctionName": { "Fn::GetAtt": [ "BackingLambdaFunction", "Arn" ] }, 88 | "Action": "lambda:InvokeFunction", 89 | "Principal": "apigateway.amazonaws.com" 90 | } 91 | }, 92 | "BackingLambdaExecutionRole": { 93 | "Type": "AWS::IAM::Role", 94 | "Properties": { 95 | "AssumeRolePolicyDocument": { 96 | "Version": "2012-10-17", 97 | "Statement": [ 98 | { 99 | "Effect": "Allow", 100 | "Principal": { 101 | "Service": [ "lambda.amazonaws.com" ] 102 | }, 103 | "Action": [ "sts:AssumeRole" ] 104 | } 105 | ] 106 | }, 107 | "Policies": [ 108 | { 109 | "PolicyName": { "Fn::Join": [ "-", [ { "Ref": "AWS::StackName" }, "UseDBPolicy" ] ] }, 110 | "PolicyDocument": { 111 | "Version": "2012-10-17", 112 | "Statement": [ 113 | { 114 | "Effect": "Allow", 115 | "Action": [ 116 | "dynamodb:DeleteItem", 117 | "dynamodb:GetItem", 118 | "dynamodb:PutItem", 119 | "dynamodb:Query", 120 | "dynamodb:Scan", 121 | "dynamodb:UpdateItem" 122 | ], 123 | "Resource": { 124 | "Fn::Join": [ 125 | "", 126 | [ 127 | "arn:aws:dynamodb:", 128 | { "Ref": "AWS::Region" }, 129 | ":", 130 | { "Ref": "AWS::AccountId" }, 131 | ":table/", 132 | { "Ref": "APIDynamoDBTable" } 133 | ] 134 | ] 135 | } 136 | }, 137 | { 138 | "Effect": "Allow", 139 | "Action": [ 140 | "logs:CreateLogGroup", 141 | "logs:CreateLogStream", 142 | "logs:PutLogEvents" 143 | ], 144 | "Resource": "*" 145 | } 146 | ] 147 | } 148 | } 149 | ] 150 | } 151 | }, 152 | "MainAPI": { 153 | "Type": "Custom::RestApi", 154 | "Properties": { 155 | "name": { "Fn::Join": [ "-", [ { "Ref": "AWS::StackName" }, { "Ref": "APIName" } ] ] }, 156 | "description": { "Ref": "APIDescription" }, 157 | "ServiceToken": { "Ref": "APIGatewayCustomResourceARN" } 158 | } 159 | }, 160 | "MainAPIResource": { 161 | "Type": "Custom::ApiResource", 162 | "Properties": { 163 | "ServiceToken": { "Ref": "APIGatewayCustomResourceARN" }, 164 | "restApiId": { "Ref": "MainAPI" }, 165 | "parentId": { "Fn::GetAtt": [ "MainAPI", "parentResourceId" ] }, 166 | "pathPart": { "Ref": "APIPath" }, 167 | "corsConfiguration": { 168 | "allowMethods": [ "GET", "POST" ], 169 | "allowHeaders": [ "x-my-header", "some-other-header" ], 170 | "allowDefaultHeaders": true, 171 | "allowOrigin": "*", 172 | "exposeHeaders": [ "some-header", "x-another-header" ], 173 | "maxAge": 1800 174 | } 175 | } 176 | }, 177 | "APIMethodGet": { 178 | "Type": "Custom::ApiMethod", 179 | "Properties": { 180 | "ServiceToken": { "Ref": "APIGatewayCustomResourceARN" }, 181 | "restApiId": { "Ref": "MainAPI" }, 182 | "resourceId": { "Ref": "MainAPIResource" }, 183 | "method": { 184 | "httpMethod": "GET", 185 | "parameters": [ 186 | "querystring.sortBy", 187 | "header.x-test-header", 188 | "path.entityType" 189 | ] 190 | }, 191 | "integration": { 192 | "type": "AWS", 193 | "uri": { 194 | "Fn::Join": [ 195 | ":", 196 | [ 197 | "arn:aws:apigateway", 198 | { "Ref": "AWS::Region" }, 199 | "lambda:path/2015-03-31/functions/arn:aws:lambda", 200 | { "Ref": "AWS::Region" }, 201 | { "Ref": "AWS::AccountId" }, 202 | "function", 203 | { "Fn::Join": [ "/", [ { "Fn::Join": [ "-", [ { "Ref": "AWS::StackName" }, { "Ref": "APIName" } ] ] }, "invocations" ] ] } 204 | ] 205 | ] 206 | }, 207 | "httpMethod": "POST", 208 | "requestTemplates": { 209 | "application/json": [ "input-pass-through-full", { 210 | "DynamoDBTableName": { "Ref": "APIDynamoDBTable" } 211 | } ] 212 | }, 213 | "requestParameters": { 214 | "integration.request.querystring.sortBy": "'hardcodedValue'" 215 | } 216 | }, 217 | "responses": { 218 | "default": { 219 | "statusCode": "200", 220 | "headers": { 221 | "X-Custom-Header": "'hardcodedValue'" 222 | } 223 | }, 224 | ".*NotFound.*": { 225 | "statusCode": "404" 226 | } 227 | } 228 | } 229 | }, 230 | "APIMethodPost": { 231 | "Type": "Custom::ApiMethod", 232 | "Properties": { 233 | "ServiceToken": { "Ref": "APIGatewayCustomResourceARN" }, 234 | "restApiId": { "Ref": "MainAPI" }, 235 | "resourceId": { "Ref": "MainAPIResource" }, 236 | "method": { 237 | "httpMethod": "POST", 238 | "parameters": [ 239 | "querystring.sortBy", 240 | "header.x-test-header", 241 | "path.entityType" 242 | ] 243 | }, 244 | "integration": { 245 | "type": "AWS", 246 | "uri": { 247 | "Fn::Join": [ 248 | ":", 249 | [ 250 | "arn:aws:apigateway", 251 | { "Ref": "AWS::Region" }, 252 | "lambda:path/2015-03-31/functions/arn:aws:lambda", 253 | { "Ref": "AWS::Region" }, 254 | { "Ref": "AWS::AccountId" }, 255 | "function", 256 | { "Fn::Join": [ "/", [ { "Fn::Join": [ "-", [ { "Ref": "AWS::StackName" }, { "Ref": "APIName" } ] ] }, "invocations" ] ] } 257 | ] 258 | ] 259 | }, 260 | "httpMethod": "POST", 261 | "requestTemplates": { 262 | "application/json": [ "input-pass-through-full", { 263 | "DynamoDBTableName": { "Ref": "APIDynamoDBTable" } 264 | } ] 265 | }, 266 | "requestParameters": { 267 | "integration.request.querystring.sortBy": "'hardcodedValue'" 268 | } 269 | }, 270 | "responses": { 271 | "default": { 272 | "statusCode": "200", 273 | "headers": { 274 | "X-Custom-Header": "'hardcodedValue'" 275 | } 276 | }, 277 | ".*NotFound.*": { 278 | "statusCode": "404" 279 | } 280 | } 281 | } 282 | }, 283 | "DeployApi": { 284 | "Type": "Custom::ApiDeploy", 285 | "DependsOn": [ "APIMethodGet", "APIMethodPost" ], 286 | "Properties": { 287 | "ServiceToken": { "Ref": "APIGatewayCustomResourceARN" }, 288 | "restApiId": { "Ref": "MainAPI" }, 289 | "stageName": { "Ref": "APIStageName" }, 290 | "stageConfig": { 291 | "cacheClusterEnabled": false 292 | }, 293 | "methodSettings": { 294 | }, 295 | "stageVariables": { 296 | "testVar1": "testValue1", 297 | "testVar2": "testValue2" 298 | } 299 | } 300 | }, 301 | "APIDynamoDBTable": { 302 | "Type": "AWS::DynamoDB::Table", 303 | "Properties": { 304 | "AttributeDefinitions": [ 305 | { 306 | "AttributeName": "GUID", 307 | "AttributeType": "S" 308 | }, 309 | { 310 | "AttributeName": "DueDate", 311 | "AttributeType": "S" 312 | } 313 | ], 314 | "KeySchema": [ 315 | { 316 | "AttributeName": "GUID", 317 | "KeyType": "HASH" 318 | }, 319 | { 320 | "AttributeName": "DueDate", 321 | "KeyType": "RANGE" 322 | } 323 | ], 324 | "ProvisionedThroughput": { 325 | "ReadCapacityUnits": { "Ref": "DynamoReadCapacityUnits" }, 326 | "WriteCapacityUnits": { "Ref": "DynamoWriteCapacityUnits" } 327 | } 328 | } 329 | } 330 | }, 331 | 332 | "Outputs": { 333 | "LambdaName": { 334 | "Value": { "Ref": "BackingLambdaFunction" }, 335 | "Description": "The Lambda function" 336 | }, 337 | "TableName": { 338 | "Value": { "Ref": "APIDynamoDBTable" }, 339 | "Description": "The DynamoDB table" 340 | }, 341 | "MainAPI": { 342 | "Value": { "Ref": "MainAPI" }, 343 | "Description": "The main API gateway" 344 | }, 345 | "APIDeployment": { 346 | "Value": { "Ref": "DeployApi" }, 347 | "Description": "The deployment of the API" 348 | } 349 | } 350 | } 351 | -------------------------------------------------------------------------------- /cloudformation/sample-params.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "ParameterKey": "APIName", 4 | "ParameterValue": "automatically-created-api" 5 | }, 6 | { 7 | "ParameterKey": "LambdaCodeBucket", 8 | "ParameterValue": "cfn-simple-lambda-api-code" 9 | }, 10 | { 11 | "ParameterKey": "LambdaCodePath", 12 | "ParameterValue": "cloudformation-template-for-lambda-backed-api-gateway-with-dynamodb.zip" 13 | }, 14 | { 15 | "ParameterKey": "APIGatewayCustomResourceARN", 16 | "ParameterValue": "arn:aws:lambda:us-east-1:123456789012:function:APIGatewayCustomResource-LambdaFunction-ABCDEFGHIJ123" 17 | } 18 | ] 19 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2016 Jeremy Thomerson 3 | * Licensed under the MIT license. 4 | */ 5 | 6 | 'use strict'; 7 | 8 | var AWS = require('aws-sdk'), 9 | dynamo = new AWS.DynamoDB.DocumentClient(); 10 | 11 | exports.handler = function(event, context, callback) { 12 | var method = event.context['http-method'].toUpperCase(); 13 | 14 | switch (method) { 15 | case 'GET': 16 | handleGet(event, context, callback); 17 | break; 18 | case 'POST': 19 | handlePost(event, context, callback); 20 | break; 21 | default: 22 | callback('Unsupported method'); 23 | } 24 | }; 25 | 26 | function handlePost(event, context, callback) { 27 | var params = { 28 | TableName: event.custom.DynamoDBTableName, 29 | // TODO: obviously there's no request validation going on here like there should be 30 | Item: { 31 | GUID: event['body-json'].GUID, 32 | DueDate: event['body-json'].DueDate, 33 | Title: event['body-json'].Title, 34 | IsCompleted: event['body-json'].IsCompleted, 35 | } 36 | }; 37 | 38 | dynamo.put(params, function(err, data) { 39 | if (err) { 40 | callback(null, { customError: 'Error adding item: ' + JSON.stringify(err, null, 2) }); 41 | } else { 42 | callback(null, { 43 | data: data 44 | }); 45 | } 46 | }); 47 | } 48 | 49 | function handleGet(event, context, callback) { 50 | var params = { 51 | TableName: event.custom.DynamoDBTableName, 52 | Limit: 10, 53 | }; 54 | 55 | dynamo.scan(params, function(err, data) { 56 | callback(null, { 57 | input: event, 58 | err: err, 59 | output: data 60 | }); 61 | }); 62 | } 63 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cloudformation-template-for-lambda-backed-api-gateway-with-dynamodb", 3 | "version": "1.0.0", 4 | "description": "An example of how to create a Lambda-backed API on AWS using API Gateway, calling your Lambda code, which uses a DynamoDB table for storage, using CloudFormation to automate the entire deployment of the API and all its pieces.", 5 | "main": "src/index.js", 6 | "dependencies": { 7 | "grunt": "^1.0.1" 8 | }, 9 | "devDependencies": { 10 | "grunt": "1.0.1", 11 | "grunt-zip": "0.17.1" 12 | }, 13 | "scripts": { 14 | "test": "echo \"Error: no test specified\" && exit 1" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/jthomerson/cloudformation-template-for-lambda-backed-api-gateway-with-dynamodb.git" 19 | }, 20 | "author": "Jeremy Thomerson", 21 | "license": "MIT", 22 | "bugs": { 23 | "url": "https://github.com/jthomerson/cloudformation-template-for-lambda-backed-api-gateway-with-dynamodb/issues" 24 | }, 25 | "homepage": "https://github.com/jthomerson/cloudformation-template-for-lambda-backed-api-gateway-with-dynamodb#readme" 26 | } 27 | --------------------------------------------------------------------------------