How to easily set up “serverless server” for IoT devices using Amazon AWS Lambda, Python, Flask & Zappa

Summary:

Why Amazon AWS Lambda?

Before we begin…

Outline:

Set up Work Environment

Amazon AWS Account & Credentials

NOTE

Create Python Working Environment

# Create working directory
mkdir my-first-lambda-project
cd my-first-lambda-project
# Update pip and install virtualenv
python3 -m pip install --user --upgrade pip
python3 -m pip install --user virtualenv
# Create virtual environment and activate it
python3 -m venv <name_of_your_virtual_environment>
source <name_of_your_virtual_environment>/bin/activate
pip3 install awscli --upgrade
aws configure
pip install flask zappa

Create RESTful Web Services using Flask & Zappa

cd my-first-lambda-project
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/device/<device_id>')
def deviceId(deviceId):
return {'deviceId': deviceId}
if __name__ == '__main__':
app.run()

Upload and Run Zappa on AWS Lambda

cd my-first-lambda-project
zappa init
zappa deploy dev
zappa update dev
https://XXXXXX.execute-api.REGION-XX-X.amazonaws.com/dev

REST API Testing

Option 1

https://XXXXXX.execute-api.REGION-XX-X.amazonaws.com/dev/device/deviceId-1
curl https://XXXXXX.execute-api.REGION-XX-X.amazonaws.com/dev/device/deviceId-1
{
"message": "deviceId-1"
}

Option 2

UI of the Restlet

Set up IoT device

Request info from AWS Lambda

pip install requests
import requests
import json
from requests.exceptions import HTTPError
URL = 'https://XXXXXX.execute-api.REGION-XX-X.amazonaws.com/dev'
API_GET_DEVICE = 'device'

def get_device(deviceId):
"""Request device information given deviceId
Arguments:
deviceId {string} -- requested information
Returns:
responseJson [json] -- API request reponse in the JSON format
"""
try:
url = '{}/{}/{}'.format(URL, API_GET_DEVICE, deviceId)
response = requests.get(url)
responseJson = json.dumps(response.json()) response.raise_for_status() except HTTPError as http_err:
print('HTTP error occurred: {}'.format(http_err))
except Exception as err:
print('Other error occurred: {}'.format(err))
else:

return responseJson
def main(): deviceId = 'deviceId-1'
responseJson = get_device(deviceId)
print(responseJson)
if __name__ == "__main__":
main()

Summary

Process summary

Part 2

Thank you

Software Developer & Data Scientist

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store