├── .gitignore ├── LICENSE ├── README.md ├── app ├── index.html └── script.js ├── docker └── docker-compose.yml ├── functions ├── get_document │ ├── __init__.py │ ├── app.py │ └── requirements.txt └── load_data │ ├── __init__.py │ ├── app.py │ └── requirements.txt ├── local-event.json └── template.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # SAM build 10 | .aws-sam/ 11 | 12 | # OSX 13 | .DS_Store 14 | 15 | # Distribution / packaging 16 | .Python 17 | build/ 18 | develop-eggs/ 19 | dist/ 20 | downloads/ 21 | eggs/ 22 | .eggs/ 23 | lib/ 24 | lib64/ 25 | parts/ 26 | sdist/ 27 | var/ 28 | wheels/ 29 | pip-wheel-metadata/ 30 | share/python-wheels/ 31 | *.egg-info/ 32 | .installed.cfg 33 | *.egg 34 | MANIFEST 35 | 36 | # PyInstaller 37 | # Usually these files are written by a python script from a template 38 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 39 | *.manifest 40 | *.spec 41 | 42 | # Installer logs 43 | pip-log.txt 44 | pip-delete-this-directory.txt 45 | 46 | # Unit test / coverage reports 47 | htmlcov/ 48 | .tox/ 49 | .nox/ 50 | .coverage 51 | .coverage.* 52 | .cache 53 | nosetests.xml 54 | coverage.xml 55 | *.cover 56 | *.py,cover 57 | .hypothesis/ 58 | .pytest_cache/ 59 | 60 | # Translations 61 | *.mo 62 | *.pot 63 | 64 | # Django stuff: 65 | *.log 66 | local_settings.py 67 | db.sqlite3 68 | db.sqlite3-journal 69 | 70 | # Flask stuff: 71 | instance/ 72 | .webassets-cache 73 | 74 | # Scrapy stuff: 75 | .scrapy 76 | 77 | # Sphinx documentation 78 | docs/_build/ 79 | 80 | # PyBuilder 81 | target/ 82 | 83 | # Jupyter Notebook 84 | .ipynb_checkpoints 85 | 86 | # IPython 87 | profile_default/ 88 | ipython_config.py 89 | 90 | # pyenv 91 | .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 101 | __pypackages__/ 102 | 103 | # Celery stuff 104 | celerybeat-schedule 105 | celerybeat.pid 106 | 107 | # SageMath parsed files 108 | *.sage.py 109 | 110 | # Environments 111 | .env 112 | .venv 113 | env/ 114 | venv/ 115 | ENV/ 116 | env.bak/ 117 | venv.bak/ 118 | 119 | # Spyder project settings 120 | .spyderproject 121 | .spyproject 122 | 123 | # Rope project settings 124 | .ropeproject 125 | 126 | # mkdocs documentation 127 | /site 128 | 129 | # mypy 130 | .mypy_cache/ 131 | .dmypy.json 132 | dmypy.json 133 | 134 | # Pyre type checker 135 | .pyre/ 136 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-lambda-sam-demo 2 | Demo project which uses SAM and AWS lambda to test lambdas locally. 3 | A company has a lot of documents. The documents have a unique ID. It's also possible to have multiple versions of one document. The employees of the company have issues to find out where a certain version of a certain document is stored. To solve this the company has developed a solution to make it easy to query the storage location of a document. 4 | 5 |  6 | 7 | # local setup 8 | 9 | Deploy DynamoDB in Docker 10 | ``` 11 | $ docker network create sam-demo 12 | $ docker run --network sam-demo --name dynamodb -d -p 8000:8000 amazon/dynamodb-local 13 | $ aws dynamodb create-table --table-name documentTable --attribute-definitions AttributeName=documentId,AttributeType=N AttributeName=versionId,AttributeType=S --key-schema AttributeName=documentId,KeyType=HASH AttributeName=versionId,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 --endpoint-url http://localhost:8000 14 | ``` 15 | 16 | Build SAM application 17 | ``` 18 | $ sam build --use-container 19 | ``` 20 | 21 | Invoke load data function to load data in DynamoDB and verify 22 | ``` 23 | $ sam local invoke LoadDataFunction --parameter-overrides ParameterKey=Environment,ParameterValue=local ParameterKey=DDBTableName,ParameterValue=documentTable --docker-network sam-demo 24 | $ aws dynamodb scan --table-name documentTable --endpoint-url http://localhost:8000 25 | ``` 26 | 27 | Start local API Gateway 28 | ``` 29 | $ sam local start-api --parameter-overrides ParameterKey=Environment,ParameterValue=local ParameterKey=DDBTableName,ParameterValue=documentTable --docker-network sam-demo 30 | ``` 31 | 32 | Test with curl 33 | ``` 34 | $ curl "http://127.0.0.1:3000/document?documentId=1044&versionId=v_1" 35 | {"message": {"location": "s3://bucket-a/8853806831.doc"}} 36 | ``` 37 | 38 | Open the static web application 39 | 40 | 41 | 42 | # AWS setup 43 | Create your `s3-bucket` in the your default region. Deploy the application using SAM CLI 44 | ``` 45 | $ sam build --use-container 46 | $ sam deploy --template-file .aws-sam/build/template.yaml --s3-bucket xxx-bucket --parameter-overrides ParameterKey=Environment,ParameterValue=aws ParameterKey=DDBTableName,ParameterValue=documentTable --stack-name aws-lambda-sam-demo --capabilities CAPABILITY_NAMED_IAM 47 | ``` 48 | 49 | Copy the static resources to the newly created S3 bucket 50 | ```bash 51 | $ aws s3 sync app s3://${bucket_name_via_sam_deploy_created} --acl public-read 52 | 53 | --- 54 | upload: app/script.js to s3://${bucket_name_via_sam_deploy_created}/script.js 55 | upload: app/index.html to s3://${bucket_name_via_sam_deploy_created}/index.html 56 | ``` 57 | 58 | Cleanup: 59 | ```bash 60 | $ aws s3 rm s3://${bucket_name_via_sam_deploy_created} --recursive 61 | 62 | --- 63 | delete: s3://${bucket_name_via_sam_deploy_created}/index.html 64 | delete: s3://${bucket_name_via_sam_deploy_created}/script.js 65 | ``` 66 | 67 | Delete stack 68 | ```bash 69 | $ aws cloudformation delete-stack --stack-name aws-lambda-sam-demo 70 | ``` 71 | -------------------------------------------------------------------------------- /app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 6 | 7 |24 | 25 | -------------------------------------------------------------------------------- /app/script.js: -------------------------------------------------------------------------------- 1 | function showInput() { 2 | docid = document.getElementById("document_id").value 3 | vid = document.getElementById("version_id").value; 4 | 5 | var result=""; 6 | $.ajax({ 7 | url: "http://127.0.0.1:3000/document?documentId=" +docid + "&versionId=" + vid, 8 | //url: "https://xxx.execute-api.eu-west-1.amazonaws.com/v1/document?documentId=" +docid + "&versionId=" + vid, 9 | async: true, 10 | type: 'GET', 11 | success:function(data) { 12 | result = data; 13 | document.getElementById('output').innerHTML = result['message']['location'] 14 | }, 15 | error:function (xhr, ajaxOptions, thrownError){ 16 | if(xhr.status==404) { 17 | document.getElementById('output').innerHTML = 'Item not found' 18 | } 19 | else { 20 | document.getElementById('output').innerHTML = 'Unexpected error' 21 | } 22 | } 23 | }); 24 | } -------------------------------------------------------------------------------- /docker/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.7' 2 | 3 | services: 4 | dynamodb: 5 | container_name: dynamodb 6 | image: amazon/dynamodb-local 7 | ports: 8 | - 8000:8000 9 | networks: 10 | - aws-local-network 11 | 12 | networks: 13 | aws-local-network: 14 | driver: bridge -------------------------------------------------------------------------------- /functions/get_document/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lvthillo/aws-lambda-sam-demo/c4c41358f8711d78202a18d82b6646922bd83c48/functions/get_document/__init__.py -------------------------------------------------------------------------------- /functions/get_document/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import boto3 4 | import logging 5 | from botocore.exceptions import ClientError 6 | 7 | logger = logging.getLogger() 8 | logger.setLevel(logging.INFO) 9 | 10 | def get_ddb_connection(): 11 | ENV = os.environ['Environment'] 12 | ddbclient='' 13 | if ENV == 'local': 14 | ddbclient = boto3.client('dynamodb', endpoint_url='http://dynamodb:8000/') 15 | else: 16 | ddbclient = boto3.client('dynamodb') 17 | return ddbclient 18 | 19 | def lambda_handler(event, context): 20 | docid = event['queryStringParameters']['documentId'] 21 | vid = event['queryStringParameters']['versionId'] 22 | 23 | try: 24 | ddbclient = get_ddb_connection() 25 | response = ddbclient.get_item( 26 | TableName=os.environ['DDBTableName'], 27 | Key={ 28 | 'documentId':{'N': docid}, 29 | 'versionId':{'S': vid} 30 | }, 31 | AttributesToGet=[ 32 | 'location', 33 | ], 34 | ) 35 | 36 | logging.info(response) 37 | 38 | if 'Item' in response: 39 | low_level_data = dict(response['Item']) 40 | 41 | boto3.resource('dynamodb') 42 | deserializer = boto3.dynamodb.types.TypeDeserializer() 43 | python_data = {k: deserializer.deserialize(v) for k,v in low_level_data.items()} 44 | logging.info(python_data) 45 | 46 | return { 47 | 'statusCode': response['ResponseMetadata']['HTTPStatusCode'], 48 | 'headers': { 49 | 'Content-Type': 'application/json', 50 | 'Access-Control-Allow-Origin':'*' 51 | }, 52 | 'body': json.dumps({ 53 | 'message': python_data, 54 | }), 55 | } 56 | 57 | else: 58 | return { 59 | 'statusCode': '404', 60 | 'headers': { 61 | 'Content-Type': 'application/json', 62 | 'Access-Control-Allow-Origin':'*' 63 | }, 64 | 'body': json.dumps({ 65 | 'message': 'Item not found', 66 | }), 67 | } 68 | 69 | except ddbclient.exceptions.ResourceNotFoundException as e: 70 | logging.error('Cannot do operations on a non-existent table') 71 | raise e 72 | except ClientError as e: 73 | logging.error('Unexpected error') 74 | raise e -------------------------------------------------------------------------------- /functions/get_document/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3 -------------------------------------------------------------------------------- /functions/load_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lvthillo/aws-lambda-sam-demo/c4c41358f8711d78202a18d82b6646922bd83c48/functions/load_data/__init__.py -------------------------------------------------------------------------------- /functions/load_data/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import boto3 4 | import logging 5 | from botocore.exceptions import ClientError 6 | 7 | logger = logging.getLogger() 8 | logger.setLevel(logging.INFO) 9 | 10 | def get_ddb_connection(): 11 | ENV = os.environ['Environment'] 12 | ddbclient='' 13 | if ENV == 'local': 14 | ddbclient = boto3.client('dynamodb', endpoint_url='http://dynamodb:8000/') 15 | else: 16 | ddbclient = boto3.client('dynamodb') 17 | return ddbclient 18 | 19 | def lambda_handler(event, context): 20 | ddbclient = get_ddb_connection() 21 | try: 22 | response = ddbclient.batch_write_item( 23 | RequestItems={ 24 | os.environ['DDBTableName']: [ 25 | { 26 | 'PutRequest': { 27 | 'Item': { 28 | 'documentId': {'N': '1043'}, 29 | 'versionId': {'S': 'v_1'}, 30 | 'location': {'S': 's3://bucket-a/6591636740.doc'} 31 | } 32 | } 33 | }, 34 | { 35 | 'PutRequest': { 36 | 'Item': { 37 | 'documentId': {'N': '1043'}, 38 | 'versionId': {'S': 'v_2'}, 39 | 'location': {'S': 's3://bucket-b/2816684052.doc'} 40 | } 41 | } 42 | }, 43 | { 44 | 'PutRequest': { 45 | 'Item': { 46 | 'documentId': {'N': '1044'}, 47 | 'versionId': {'S': 'v_1'}, 48 | 'location': {'S': 's3://bucket-a/8853806831.doc'} 49 | } 50 | } 51 | }, 52 | { 53 | 'PutRequest': { 54 | 'Item': { 55 | 'documentId': {'N': '1045'}, 56 | 'versionId': {'S': 'v_1'}, 57 | 'location': {'S': 's3://bucket-a/7100394559.doc'} 58 | } 59 | } 60 | }, 61 | { 62 | 'PutRequest': { 63 | 'Item': { 64 | 'documentId': {'N': '1045'}, 65 | 'versionId': {'S': 'v_2'}, 66 | 'location': {'S': 's3://bucket-c/2897476413.doc'} 67 | } 68 | } 69 | }, 70 | ]} 71 | ) 72 | 73 | return { 74 | 'statusCode': response['ResponseMetadata']['HTTPStatusCode'], 75 | 'body': json.dumps({ 76 | 'message': 'Filled DynamoDB', 77 | }), 78 | } 79 | 80 | except ddbclient.exceptions.ResourceNotFoundException as e: 81 | logging.error('Cannot do operations on a non-existent table') 82 | raise e 83 | except ClientError as e: 84 | logging.error('Unexpected error') 85 | raise e 86 | 87 | -------------------------------------------------------------------------------- /functions/load_data/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3 -------------------------------------------------------------------------------- /local-event.json: -------------------------------------------------------------------------------- 1 | { 2 | "body": "", 3 | "resource": "/{proxy+}", 4 | "path": "/document", 5 | "httpMethod": "GET", 6 | "isBase64Encoded": true, 7 | "queryStringParameters": { 8 | "documentId": "1044", 9 | "versionId": "v_1" 10 | }, 11 | "multiValueQueryStringParameters": { 12 | "foo": [ 13 | "bar" 14 | ] 15 | }, 16 | "pathParameters": { 17 | "proxy": "/document" 18 | }, 19 | "stageVariables": { 20 | "baz": "qux" 21 | }, 22 | "headers": { 23 | "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", 24 | "Accept-Encoding": "gzip, deflate, sdch", 25 | "Accept-Language": "en-US,en;q=0.8", 26 | "Cache-Control": "max-age=0", 27 | "CloudFront-Forwarded-Proto": "https", 28 | "CloudFront-Is-Desktop-Viewer": "true", 29 | "CloudFront-Is-Mobile-Viewer": "false", 30 | "CloudFront-Is-SmartTV-Viewer": "false", 31 | "CloudFront-Is-Tablet-Viewer": "false", 32 | "CloudFront-Viewer-Country": "US", 33 | "Host": "1234567890.execute-api.us-east-1.amazonaws.com", 34 | "Upgrade-Insecure-Requests": "1", 35 | "User-Agent": "Custom User Agent String", 36 | "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", 37 | "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", 38 | "X-Forwarded-For": "127.0.0.1, 127.0.0.2", 39 | "X-Forwarded-Port": "443", 40 | "X-Forwarded-Proto": "https" 41 | }, 42 | "multiValueHeaders": { 43 | "Accept": [ 44 | "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" 45 | ], 46 | "Accept-Encoding": [ 47 | "gzip, deflate, sdch" 48 | ], 49 | "Accept-Language": [ 50 | "en-US,en;q=0.8" 51 | ], 52 | "Cache-Control": [ 53 | "max-age=0" 54 | ], 55 | "CloudFront-Forwarded-Proto": [ 56 | "https" 57 | ], 58 | "CloudFront-Is-Desktop-Viewer": [ 59 | "true" 60 | ], 61 | "CloudFront-Is-Mobile-Viewer": [ 62 | "false" 63 | ], 64 | "CloudFront-Is-SmartTV-Viewer": [ 65 | "false" 66 | ], 67 | "CloudFront-Is-Tablet-Viewer": [ 68 | "false" 69 | ], 70 | "CloudFront-Viewer-Country": [ 71 | "US" 72 | ], 73 | "Host": [ 74 | "0123456789.execute-api.us-east-1.amazonaws.com" 75 | ], 76 | "Upgrade-Insecure-Requests": [ 77 | "1" 78 | ], 79 | "User-Agent": [ 80 | "Custom User Agent String" 81 | ], 82 | "Via": [ 83 | "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)" 84 | ], 85 | "X-Amz-Cf-Id": [ 86 | "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==" 87 | ], 88 | "X-Forwarded-For": [ 89 | "127.0.0.1, 127.0.0.2" 90 | ], 91 | "X-Forwarded-Port": [ 92 | "443" 93 | ], 94 | "X-Forwarded-Proto": [ 95 | "https" 96 | ] 97 | }, 98 | "requestContext": { 99 | "accountId": "123456789012", 100 | "resourceId": "123456", 101 | "stage": "prod", 102 | "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", 103 | "requestTime": "09/Apr/2015:12:34:56 +0000", 104 | "requestTimeEpoch": 1428582896000, 105 | "identity": { 106 | "cognitoIdentityPoolId": null, 107 | "accountId": null, 108 | "cognitoIdentityId": null, 109 | "caller": null, 110 | "accessKey": null, 111 | "sourceIp": "127.0.0.1", 112 | "cognitoAuthenticationType": null, 113 | "cognitoAuthenticationProvider": null, 114 | "userArn": null, 115 | "userAgent": "Custom User Agent String", 116 | "user": null 117 | }, 118 | "path": "/prod/document", 119 | "resourcePath": "/{proxy+}", 120 | "httpMethod": "GET", 121 | "apiId": "1234567890", 122 | "protocol": "HTTP/1.1" 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | Description: SAM Template for SAM demo application 4 | 5 | Globals: 6 | Function: 7 | Timeout: 5 8 | Api: 9 | Cors: 10 | AllowMethods: "'GET,OPTIONS'" 11 | AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'" 12 | AllowOrigin: "'*'" 13 | 14 | Parameters: 15 | Environment: 16 | Type: String 17 | Description: Choose between local or AWS 18 | AllowedValues: 19 | - local 20 | - aws 21 | DDBTableName: 22 | Type: String 23 | Description: The name of the DynamoDB tablename 24 | 25 | Resources: 26 | ################### 27 | ## Lambdas ## 28 | ################### 29 | # lambda function to load initial data 30 | LoadDataFunction: 31 | Type: AWS::Serverless::Function 32 | Properties: 33 | CodeUri: ./functions/load_data 34 | Handler: app.lambda_handler 35 | Runtime: python3.7 36 | FunctionName: LoadDataFunction 37 | Environment: 38 | Variables: 39 | Environment: !Ref Environment 40 | DDBTableName: !Ref DDBTableName 41 | Policies: 42 | - Version: '2012-10-17' 43 | Statement: 44 | - Effect: Allow 45 | Action: 46 | - logs:CreateLogGroup 47 | - logs:CreateLogStream 48 | - logs:PutLogEvents 49 | Resource: arn:aws:logs:*:*:* 50 | - Effect: Allow 51 | Action: 52 | - dynamodb:BatchWriteItem 53 | Resource: !GetAtt DocumentTable.Arn 54 | # lambda function to get document location based on documentId and versionId 55 | GetDocumentFunction: 56 | Type: AWS::Serverless::Function 57 | Properties: 58 | CodeUri: functions/get_document/ 59 | Handler: app.lambda_handler 60 | Runtime: python3.7 61 | FunctionName: GetDocumentFunction 62 | Events: 63 | GetDocument: 64 | Type: Api 65 | Properties: 66 | Path: /document 67 | Method: get 68 | RequestParameters: 69 | - method.request.querystring.documentId 70 | - method.request.querystring.versionId 71 | RestApiId: !Ref MyApi 72 | Environment: 73 | Variables: 74 | Environment: !Ref Environment 75 | DDBTableName: !Ref DDBTableName 76 | Policies: 77 | - Version: '2012-10-17' 78 | Statement: 79 | - Effect: Allow 80 | Action: 81 | - logs:CreateLogGroup 82 | - logs:CreateLogStream 83 | - logs:PutLogEvents 84 | Resource: arn:aws:logs:*:*:* 85 | - Effect: Allow 86 | Action: 87 | - dynamodb:getItem 88 | Resource: !GetAtt DocumentTable.Arn 89 | # API stage 90 | MyApi: 91 | Type: AWS::Serverless::Api 92 | Properties: 93 | StageName: v1 94 | 95 | ########################## 96 | ## DynamoDB Table ## 97 | ########################## 98 | # DynamoDB table to store documentId, versionId and document location 99 | DocumentTable: 100 | Type: AWS::DynamoDB::Table 101 | Properties: 102 | AttributeDefinitions: 103 | - 104 | AttributeName: 'documentId' 105 | AttributeType: 'N' 106 | - 107 | AttributeName: 'versionId' 108 | AttributeType: 'S' 109 | KeySchema: 110 | - 111 | AttributeName: 'documentId' 112 | KeyType: 'HASH' 113 | - 114 | AttributeName: 'versionId' 115 | KeyType: 'RANGE' 116 | TableName: !Ref DDBTableName 117 | ProvisionedThroughput: 118 | ReadCapacityUnits: 5 119 | WriteCapacityUnits: 5 120 | 121 | ########################## 122 | ## Static S3 webapp ## 123 | ########################## 124 | S3Bucket: 125 | Type: AWS::S3::Bucket 126 | Properties: 127 | AccessControl: PublicRead 128 | WebsiteConfiguration: 129 | IndexDocument: index.html 130 | 131 | Outputs: 132 | GetDocumentApi: 133 | Description: API Gateway endpoint URL to get document location based on documentId and versionId 134 | Value: !Sub https://${MyApi}.execute-api.${AWS::Region}.amazonaws.com/v1/document 135 | WebsiteURL: 136 | Value: !GetAtt S3Bucket.WebsiteURL 137 | Description: URL for static site hosted on S3 --------------------------------------------------------------------------------