├── .gitignore ├── LICENSE ├── README.md ├── api_auth.py ├── app.py ├── config.py ├── connector.py ├── package-lock.json ├── package.json ├── requirements.txt ├── serverless-template.yml ├── sqlapi.py └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | serverless.yml 2 | node_modules 3 | venv 4 | .serverless 5 | __pycache__ 6 | .DS_Store 7 | -------------------------------------------------------------------------------- /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 | # A Simple API Powered by Snowflake 2 | 3 | Technologies used: [Snowflake](https://snowflake.com/), [Python](https://www.python.org/), [Flask](https://palletsprojects.com/p/flask/), [AWS API Gateway](https://aws.amazon.com/api-gateway/), [AWS Lambda](https://aws.amazon.com/lambda/), [Serverless Framework](https://www.serverless.com/) 4 | 5 | Requirements: 6 | * Snowflake.com and Serverless.com account 7 | * node.js, python 3, virtualenv installed 8 | * Citibike data loaded into Snowflake 9 | * Snowflake user authorized to access citibike data with key pair authentication 10 | 11 | This project demonstrates how to build and deploy a custom API powered by Snowflake. It uses a simple Python Flask API service running on AWS Lambda using Serverless Framework. Connectivity to Snowflake is made via key pair authentication. 12 | 13 | ## Configuration 14 | 15 | Copy the serverless-template.yml to serverless.yml and modify the parameters according to your Snowflake configuration. Put your private key 16 | to your Snowflake user in AWS SSM is us-west-2 region under the parameter .DATA_APPS_DEMO. 17 | 18 | Install serverless and other required node packages and configure serverless (sls) for the project. 19 | 20 | ```bash 21 | npm install 22 | sls login 23 | ``` 24 | 25 | Create a virtualenv locally and install python packages. 26 | 27 | ```bash 28 | virtualenv venv --python=python3 29 | source ./venv/bin/activate 30 | pip install -r requirements.txt 31 | ``` 32 | 33 | ## Local Development 34 | 35 | For local development you will want to use the venv previously created. This will run a local application server and connect to your Snowflake account for data access. 36 | 37 | Start the local serverless server. 38 | 39 | ```bash 40 | sls wsgi serve 41 | ``` 42 | 43 | ### Invocation 44 | 45 | After successful startup, you can call the created application via HTTP: 46 | 47 | ```bash 48 | curl http://localhost:5000/ 49 | ``` 50 | 51 | Which should result in the following response: 52 | 53 | ```json 54 | {"result":"Nothing to see here", "time_ms": 0} 55 | ``` 56 | 57 | ## Deployment 58 | 59 | Build and deploy the application to AWS. For your first time, you will have to run sls without deploy to configure the project. 60 | 61 | ```bash 62 | sls deploy 63 | ``` 64 | 65 | ### Invocation 66 | 67 | After successful deployment, you can call the created application via HTTP: 68 | 69 | ```bash 70 | curl https://xxxxxxx.execute-api.us-west-2.amazonaws.com/dev/ 71 | ``` 72 | 73 | Which should result in the following response: 74 | 75 | ```json 76 | {"result":"Nothing to see here", "time_ms": 0} 77 | ``` 78 | 79 | ## Scaling 80 | 81 | By default, AWS Lambda limits the total concurrent executions across all functions within a given region to 1000. The default limit is a safety limit that protects you from costs due to potential runaway or recursive functions during initial development and testing. To increase this limit above the default, follow the steps in [To request a limit increase for concurrent executions](http://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html#increase-concurrent-executions-limit). -------------------------------------------------------------------------------- /api_auth.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.primitives.serialization import load_pem_private_key 2 | from cryptography.hazmat.primitives.serialization import Encoding 3 | from cryptography.hazmat.primitives.serialization import PublicFormat 4 | from cryptography.hazmat.backends import default_backend 5 | from datetime import timedelta, timezone, datetime 6 | import base64 7 | from getpass import getpass 8 | import hashlib 9 | import logging 10 | import jwt 11 | from typing import Text 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | ISSUER = "iss" 16 | EXPIRE_TIME = "exp" 17 | ISSUE_TIME = "iat" 18 | SUBJECT = "sub" 19 | 20 | def get_private_key_passphrase(): 21 | return getpass('Passphrase for private key: ') 22 | 23 | class JWTGenerator(object): 24 | """ 25 | Creates and signs a JWT with the specified private key file, username, and account identifier. The JWTGenerator keeps the 26 | generated token and only regenerates the token if a specified period of time has passed. 27 | """ 28 | LIFETIME = timedelta(minutes=59) # The tokens will have a 59 minute lifetime 29 | RENEWAL_DELTA = timedelta(minutes=54) # Tokens will be renewed after 54 minutes 30 | ALGORITHM = "RS256" # Tokens will be generated using RSA with SHA256 31 | 32 | def __init__(self, account: Text, user: Text, private_key: Text, 33 | lifetime: timedelta = LIFETIME, renewal_delay: timedelta = RENEWAL_DELTA): 34 | """ 35 | __init__ creates an object that generates JWTs for the specified user, account identifier, and private key. 36 | :param account: Your Snowflake account identifier. See https://docs.snowflake.com/en/user-guide/admin-account-identifier.html. Note that if you are using the account locator, exclude any region information from the account locator. 37 | :param user: The Snowflake username. 38 | :param private_key: Private key file used for signing the JWTs. 39 | :param lifetime: The number of minutes (as a timedelta) during which the key will be valid. 40 | :param renewal_delay: The number of minutes (as a timedelta) from now after which the JWT generator should renew the JWT. 41 | """ 42 | 43 | logger.info( 44 | """Creating JWTGenerator with arguments 45 | account : %s, user : %s, lifetime : %s, renewal_delay : %s""", 46 | account, user, lifetime, renewal_delay) 47 | 48 | # Construct the fully qualified name of the user in uppercase. 49 | self.account = self.prepare_account_name_for_jwt(account) 50 | self.user = user.upper() 51 | self.qualified_username = self.account + "." + self.user 52 | 53 | self.lifetime = lifetime 54 | self.renewal_delay = renewal_delay 55 | self.renew_time = datetime.now(timezone.utc) 56 | self.token = None 57 | self.private_key = load_pem_private_key(private_key.encode('utf-8'), None, default_backend()) 58 | 59 | 60 | def prepare_account_name_for_jwt(self, raw_account: Text) -> Text: 61 | """ 62 | Prepare the account identifier for use in the JWT. 63 | For the JWT, the account identifier must not include the subdomain or any region or cloud provider information. 64 | :param raw_account: The specified account identifier. 65 | :return: The account identifier in a form that can be used to generate JWT. 66 | """ 67 | account = raw_account 68 | if not '.global' in account: 69 | # Handle the general case. 70 | idx = account.find('.') 71 | if idx > 0: 72 | account = account[0:idx] 73 | else: 74 | # Handle the replication case. 75 | idx = account.find('-') 76 | if idx > 0: 77 | account = account[0:idx] 78 | # Use uppercase for the account identifier. 79 | return account.upper() 80 | 81 | def get_token(self) -> Text: 82 | """ 83 | Generates a new JWT. If a JWT has been already been generated earlier, return the previously generated token unless the 84 | specified renewal time has passed. 85 | :return: the new token 86 | """ 87 | now = datetime.now(timezone.utc) # Fetch the current time 88 | 89 | # If the token has expired or doesn't exist, regenerate the token. 90 | if self.token is None or self.renew_time <= now: 91 | logger.info("Generating a new token because the present time (%s) is later than the renewal time (%s)", 92 | now, self.renew_time) 93 | # Calculate the next time we need to renew the token. 94 | self.renew_time = now + self.renewal_delay 95 | 96 | # Prepare the fields for the payload. 97 | # Generate the public key fingerprint for the issuer in the payload. 98 | public_key_fp = self.calculate_public_key_fingerprint(self.private_key) 99 | 100 | # Create our payload 101 | payload = { 102 | # Set the issuer to the fully qualified username concatenated with the public key fingerprint. 103 | ISSUER: self.qualified_username + '.' + public_key_fp, 104 | 105 | # Set the subject to the fully qualified username. 106 | SUBJECT: self.qualified_username, 107 | 108 | # Set the issue time to now. 109 | ISSUE_TIME: now, 110 | 111 | # Set the expiration time, based on the lifetime specified for this object. 112 | EXPIRE_TIME: now + self.lifetime 113 | } 114 | 115 | # Regenerate the actual token 116 | token = jwt.encode(payload, key=self.private_key, algorithm=JWTGenerator.ALGORITHM) 117 | # If you are using a version of PyJWT prior to 2.0, jwt.encode returns a byte string, rather than a string. 118 | # If the token is a byte string, convert it to a string. 119 | if isinstance(token, bytes): 120 | token = token.decode('utf-8') 121 | self.token = token 122 | logger.info("Generated a JWT with the following payload: %s", jwt.decode(self.token, key=self.private_key.public_key(), algorithms=[JWTGenerator.ALGORITHM])) 123 | 124 | return self.token 125 | 126 | def calculate_public_key_fingerprint(self, private_key: Text) -> Text: 127 | """ 128 | Given a private key in PEM format, return the public key fingerprint. 129 | :param private_key: private key string 130 | :return: public key fingerprint 131 | """ 132 | # Get the raw bytes of public key. 133 | public_key_raw = private_key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) 134 | 135 | # Get the sha256 hash of the raw bytes. 136 | sha256hash = hashlib.sha256() 137 | sha256hash.update(public_key_raw) 138 | 139 | # Base64-encode the value and prepend the prefix 'SHA256:'. 140 | public_key_fp = 'SHA256:' + base64.b64encode(sha256hash.digest()).decode('utf-8') 141 | logger.info("Public key fingerprint is %s", public_key_fp) 142 | 143 | return public_key_fp 144 | 145 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, jsonify, make_response 2 | 3 | from connector import connector 4 | from sqlapi import sqlapi 5 | from utils import api_response 6 | from json import JSONEncoder 7 | 8 | app = Flask(__name__) 9 | app.register_blueprint(connector) 10 | app.register_blueprint(sqlapi) 11 | 12 | @app.route("/") 13 | @api_response 14 | def default(): 15 | return 'Nothing to see here' 16 | 17 | @app.errorhandler(404) 18 | def resource_not_found(e): 19 | return make_response(jsonify(error='Not found!'), 404) 20 | 21 | class JsonEncoder(JSONEncoder): 22 | def default(self, obj): 23 | if isinstance(obj, decimal.Decimal): 24 | return float(obj) 25 | return JSONEncoder.default(self, obj) 26 | 27 | app.json_encoder = JsonEncoder 28 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import os 2 | SNOWFLAKE_ACCOUNT = os.getenv("SNOWFLAKE_ACCOUNT") 3 | SNOWFLAKE_USER = os.getenv("SNOWFLAKE_USER") 4 | SNOWFLAKE_PRIVATE_KEY = os.getenv("SNOWFLAKE_PRIVATE_KEY") 5 | SNOWFLAKE_DATABASE = os.getenv("SNOWFLAKE_DATABASE") 6 | SNOWFLAKE_SCHEMA = os.getenv("SNOWFLAKE_SCHEMA") 7 | SNOWFLAKE_WAREHOUSE = os.getenv("SNOWFLAKE_WAREHOUSE") -------------------------------------------------------------------------------- /connector.py: -------------------------------------------------------------------------------- 1 | import config 2 | import snowflake.connector 3 | from flask import Blueprint, request 4 | 5 | from cryptography.hazmat.backends import default_backend 6 | from cryptography.hazmat.primitives import serialization 7 | 8 | from utils import api_response, params_valid 9 | 10 | 11 | def connect(): 12 | p_key = serialization.load_pem_private_key( 13 | config.SNOWFLAKE_PRIVATE_KEY.encode('utf-8'), 14 | password=None, 15 | backend=default_backend() 16 | ) 17 | pkb = p_key.private_bytes( 18 | encoding=serialization.Encoding.DER, 19 | format=serialization.PrivateFormat.PKCS8, 20 | encryption_algorithm=serialization.NoEncryption()) 21 | 22 | snowflake.connector.paramstyle='qmark' 23 | conn = snowflake.connector.connect( 24 | user=config.SNOWFLAKE_USER, 25 | account=config.SNOWFLAKE_ACCOUNT, 26 | warehouse=config.SNOWFLAKE_WAREHOUSE, 27 | schema=config.SNOWFLAKE_SCHEMA, 28 | database=config.SNOWFLAKE_DATABASE, 29 | private_key=pkb, 30 | session_parameters={ 31 | 'QUERY_TAG': 'Snowflake-Python-Connector', 32 | }) 33 | 34 | return conn 35 | 36 | 37 | conn = connect() 38 | connector = Blueprint('connector', __name__) 39 | 40 | 41 | def exec_and_fetch(sql, params = None): 42 | cur = conn.cursor().execute(sql, params) 43 | return cur.fetchall() 44 | 45 | 46 | @connector.route("/trips/monthly") 47 | @api_response 48 | def get_trips_monthly(): 49 | start_range = request.args.get('start_range') 50 | end_range = request.args.get('end_range') 51 | if start_range and end_range and params_valid(start_range, end_range): 52 | sql = f"select COUNT(*) as trip_count, MONTHNAME(starttime) as month from demo.trips where starttime between '{start_range}' and '{end_range}' group by MONTH(starttime), MONTHNAME(starttime) order by MONTH(starttime);" 53 | return exec_and_fetch(sql) 54 | sql = "select COUNT(*) as trip_count, MONTHNAME(starttime) as month from demo.trips group by MONTH(starttime), MONTHNAME(starttime) order by MONTH(starttime);" 55 | return exec_and_fetch(sql) 56 | 57 | 58 | @connector.route("/trips/day_of_week") 59 | @api_response 60 | def get_day_of_week(): 61 | start_range = request.args.get('start_range') 62 | end_range = request.args.get('end_range') 63 | if start_range and end_range and params_valid(start_range, end_range): 64 | sql = f"select COUNT(*) as trip_count, DAYNAME(starttime) as day_of_week from demo.trips where starttime between '{start_range}' and '{end_range}' group by DAYOFWEEK(starttime), DAYNAME(starttime) order by DAYOFWEEK(starttime);" 65 | return exec_and_fetch(sql) 66 | sql = "select COUNT(*) as trip_count, DAYNAME(starttime) as day_of_week from demo.trips group by DAYOFWEEK(starttime), DAYNAME(starttime) order by DAYOFWEEK(starttime);" 67 | return exec_and_fetch(sql) 68 | 69 | 70 | @connector.route("/trips/temperature") 71 | @api_response 72 | def get_temperature(): 73 | start_range = request.args.get('start_range') 74 | end_range = request.args.get('end_range') 75 | if start_range and end_range and params_valid(start_range, end_range): 76 | sql = f"with weather_trips as (select * from demo.trips t inner join demo.weather w on date_trunc(\"day\", t.starttime) = w.observation_date) select round(temp_avg_f, -1) as temp, count(*) as trip_count from weather_trips where starttime between '{start_range}' and '{end_range}' group by round(temp_avg_f, -1) order by round(temp_avg_f, -1) asc;" 77 | return exec_and_fetch(sql) 78 | sql = "with weather_trips as (select * from demo.trips t inner join demo.weather w on date_trunc(\"day\", t.starttime) = w.observation_date) select round(temp_avg_f, -1) as temp, count(*) as trip_count from weather_trips group by round(temp_avg_f, -1) order by round(temp_avg_f, -1) asc;" 79 | return exec_and_fetch(sql) -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "aws-python-flask-api", 3 | "version": "1.0.0", 4 | "description": "Example of a Python Flask API service with traditional Serverless Framework", 5 | "author": "", 6 | "devDependencies": { 7 | "serverless-offline": "^8.7.0", 8 | "serverless-python-requirements": "^6.0.1", 9 | "serverless-wsgi": "^3.0.3" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==1.5.1 2 | blinker==1.7.0 3 | certifi==2023.7.22 4 | cffi==1.17.1 5 | charset-normalizer==3.3.2 6 | click==8.1.7 7 | cryptography==41.0.5 8 | filelock==3.13.1 9 | Flask==3.0.0 10 | idna==3.4 11 | itsdangerous==2.1.2 12 | Jinja2==3.1.2 13 | MarkupSafe==2.1.3 14 | packaging==23.2 15 | platformdirs==3.11.0 16 | pycparser==2.21 17 | PyJWT==2.8.0 18 | pyOpenSSL==23.3.0 19 | pytz==2023.3.post1 20 | requests==2.31.0 21 | serverless-wsgi==3.0.3 22 | snowflake-connector-python==3.15.0 23 | sortedcontainers==2.4.0 24 | tomlkit==0.12.2 25 | typing_extensions==4.8.0 26 | urllib3==1.26.18 27 | Werkzeug==3.0.1 28 | -------------------------------------------------------------------------------- /serverless-template.yml: -------------------------------------------------------------------------------- 1 | service: 2 | frameworkVersion: '3' 3 | 4 | custom: 5 | wsgi: 6 | app: app.app 7 | packRequirements: false 8 | pythonRequirements: 9 | dockerizePip: non-linux 10 | layer: true 11 | 12 | provider: 13 | name: aws 14 | runtime: python3.11 15 | lambdaHashingVersion: '20201221' 16 | region: us-west-2 17 | 18 | functions: 19 | api: 20 | handler: wsgi_handler.handler 21 | layers: 22 | - {Ref: PythonRequirementsLambdaLayer} 23 | environment: 24 | SNOWFLAKE_ACCOUNT: '' 25 | SNOWFLAKE_USER: 'DATA_APPS_DEMO' 26 | SNOWFLAKE_DATABASE: 'DATA_APPS_DEMO' 27 | SNOWFLAKE_SCHEMA: 'DEMO' 28 | SNOWFLAKE_WAREHOUSE: 'DATA_APPS_DEMO' 29 | SNOWFLAKE_PRIVATE_KEY: ${ssm:/.DATA_APPS_DEMO} 30 | timeout: 15 31 | events: 32 | - http: 33 | path: /trips/monthly 34 | method: GET 35 | - http: 36 | path: /trips/day_of_week 37 | method: GET 38 | - http: 39 | path: /trips/temperature 40 | method: GET 41 | - http: 42 | path: /sqlapi/trips/monthly 43 | method: GET 44 | - http: 45 | path: /sqlapi/trips/day_of_week 46 | method: GET 47 | - http: 48 | path: /sqlapi/trips/temperature 49 | method: GET 50 | 51 | plugins: 52 | - serverless-wsgi 53 | - serverless-python-requirements 54 | 55 | package: 56 | patterns: 57 | - '!__pycache__/**' 58 | - '!node_modules/**' 59 | - '!.venv/**' 60 | - '!.serverless/**' 61 | - '!LICENSE' 62 | - '!README.md' 63 | - '!serverless-template.yml' 64 | - '!requirements.txt' 65 | - '!package.json' 66 | - '!package-lock.json' 67 | 68 | -------------------------------------------------------------------------------- /sqlapi.py: -------------------------------------------------------------------------------- 1 | import config 2 | import requests 3 | import uuid 4 | from datetime import timedelta 5 | from flask import Blueprint, request 6 | 7 | from api_auth import JWTGenerator 8 | from utils import api_response, params_valid 9 | 10 | 11 | sqlapi = Blueprint('sqlapi', __name__) 12 | authfn = JWTGenerator(config.SNOWFLAKE_ACCOUNT, config.SNOWFLAKE_USER, config.SNOWFLAKE_PRIVATE_KEY, timedelta(59), timedelta(54)).get_token 13 | http_session = requests.Session() 14 | url_base = f"https://{config.SNOWFLAKE_ACCOUNT}.snowflakecomputing.com" 15 | 16 | HEADERS = { 17 | "Authorization": "Bearer " + authfn(), 18 | "Content-Type": "application/json", 19 | "Snowflake-Account": config.SNOWFLAKE_ACCOUNT, 20 | "Accept": "application/json", 21 | "X-Snowflake-Authorization-Token-Type": "KEYPAIR_JWT" 22 | } 23 | 24 | 25 | def sql2body(sql): 26 | result = { 27 | "statement": f"{sql}", 28 | "timeout": 60, 29 | "resultSetMetaData": { 30 | "format": "json" 31 | }, 32 | "database": config.SNOWFLAKE_DATABASE, 33 | "schema": config.SNOWFLAKE_SCHEMA, 34 | "warehouse": config.SNOWFLAKE_WAREHOUSE, 35 | "parameters": {"query_tag": "Snowflake-Python-SQLApi"}, 36 | } 37 | return result 38 | 39 | 40 | def exec_and_fetch(sql): 41 | jsonBody = sql2body(sql) 42 | r = http_session.post(f"{url_base}/api/v2/statements?requestId={str(uuid.uuid4())}&retry=true", json=jsonBody, headers=HEADERS) 43 | if r.status_code == 200: 44 | result = r.json()['data'] 45 | return result 46 | else: 47 | print(f"ERROR: Status code from {sql}: {r.status_code}") 48 | raise Exception("Invalid response from API") 49 | 50 | 51 | @sqlapi.route("/sqlapi/trips/monthly") 52 | @api_response 53 | def get_trips_monthly(): 54 | start_range = request.args.get('start_range') 55 | end_range = request.args.get('end_range') 56 | if start_range and end_range and params_valid(start_range, end_range): 57 | sql = f"select COUNT(*) as trip_count, MONTHNAME(starttime) as month from demo.trips where starttime between '{start_range}' and '{end_range}' group by MONTH(starttime), MONTHNAME(starttime) order by MONTH(starttime);" 58 | return exec_and_fetch(sql) 59 | sql = "select COUNT(*) as trip_count, MONTHNAME(starttime) as month from demo.trips group by MONTH(starttime), MONTHNAME(starttime) order by MONTH(starttime);" 60 | return exec_and_fetch(sql) 61 | 62 | 63 | @sqlapi.route("/sqlapi/trips/day_of_week") 64 | @api_response 65 | def get_day_of_week(): 66 | start_range = request.args.get('start_range') 67 | end_range = request.args.get('end_range') 68 | if start_range and end_range and params_valid(start_range, end_range): 69 | sql = f"select COUNT(*) as trip_count, DAYNAME(starttime) as day_of_week from demo.trips where starttime between '{start_range}' and '{end_range}' group by DAYOFWEEK(starttime), DAYNAME(starttime) order by DAYOFWEEK(starttime);" 70 | return exec_and_fetch(sql) 71 | sql = "select COUNT(*) as trip_count, DAYNAME(starttime) as day_of_week from demo.trips group by DAYOFWEEK(starttime), DAYNAME(starttime) order by DAYOFWEEK(starttime);" 72 | return exec_and_fetch(sql) 73 | 74 | 75 | @sqlapi.route("/sqlapi/trips/temperature") 76 | @api_response 77 | def get_temperature(): 78 | start_range = request.args.get('start_range') 79 | end_range = request.args.get('end_range') 80 | if start_range and end_range and params_valid(start_range, end_range): 81 | sql = f"with weather_trips as (select * from demo.trips t inner join demo.weather w on date_trunc(\"day\", t.starttime) = w.observation_date) select round(temp_avg_f, -1) as temp, count(*) as trip_count from weather_trips where starttime between '{start_range}' and '{end_range}' group by round(temp_avg_f, -1) order by round(temp_avg_f, -1) asc;" 82 | return exec_and_fetch(sql) 83 | sql = "with weather_trips as (select * from demo.trips t inner join demo.weather w on date_trunc(\"day\", t.starttime) = w.observation_date) select round(temp_avg_f, -1) as temp, count(*) as trip_count from weather_trips group by round(temp_avg_f, -1) order by round(temp_avg_f, -1) asc;" 84 | return exec_and_fetch(sql) -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import functools, time, re 2 | 3 | from flask import jsonify, make_response 4 | 5 | 6 | def params_valid(start_range, end_range): 7 | if re.search("^[0-9]{2}/[0-9]{2}/[0-9]{4}$", start_range) and re.search("^[0-9]{2}/[0-9]{2}/[0-9]{4}$", end_range): 8 | return True 9 | return False 10 | 11 | 12 | def api_response(func): 13 | @functools.wraps(func) 14 | def f(*args, **kwargs): 15 | start_time = time.perf_counter() 16 | result = func(*args, **kwargs) 17 | end_time = time.perf_counter() 18 | run_time = end_time - start_time 19 | response = dict(result=result, time_ms=int(run_time*1000)) 20 | value = make_response(jsonify(response)) 21 | value.headers['Access-Control-Allow-Origin'] = '*' 22 | return value 23 | return f 24 | --------------------------------------------------------------------------------