- Consulting
- Training
- Partners
- About Us
x
Most data from IoT applications are stored in databases for convenient access via APIs. This blog talks about the methods for an API Gateway to construct an API to retrieve data from DynamoDB database tables. These APIs are also utilized in mobile and web applications.
In my previous blog, Step-by-Step Guide to Store IoT data into S3 Bucket, we get an insight on cost reduction by using AWS S3 bucket. You will be able to learn techniques to store IoT data in DynamoDB using IoT rules.
We will create a DynamoDB table and manually inject data into it and an API to access the data in the next segment.
Go to the DynamoDB Service in the AWS Console by typing DynamoDB in the search box. Click the Tables option on DynamoDB’s left side blade, then the Create Table option to create a new table.
Enter the Table name as IoT_table, the primary key as the partition key, the name as device_id, and choose the Number option next to the field. Enter the date in the field of the Sort key and pick the String option next to it. Finally, click create table option at the bottom.
We can see that the table has been created and is Active.
To inject the data into the database, go to the Actions blade and select Create item on the newly formed IoT_table.
Enter {“device_id”: 1, “date”: “07-03-2022″,”temperature”:34,”humidity”:60,”co2″:670} in the Attributes area, then click Create item. Create objects with varying values in the same way.
To verify the injected data, click on Explore table item
At the bottom of the item returned section, all created items will be displayed.
Enter IAM in the search box of the AWS console to access the IAM service. Click IAM Role on the left side blade of the IAM service, to create a new Role click Create Role on the console and select Lambda from the services then click Next. Look for DynamoDB in the permission policy area and select AmazonDynamoDBReadOnlyAcces this policy grants lambda to access the DynamoDB table’s data, then click Next and enter the Role name as dynamodb-and-lambda-role finally click Create role. As a matter of time, a role will be created.
Type lambda into the AWS search box, then select Lambda from the services menu and navigate to the lambda console. To create a new lambda function, Click Create function.
Enter Function name as IoT_API_lambda, select Runtime as Python 3.9.
In the Execution role section, select the Use an existing role option, dynamodb-and-lambda-role, and finally click Create function
Paste the following code in the lambda_function.py files in the Code Source section. This code will handle the incoming API and will provide the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<span style="color: #000000;">import boto3 import json import logging from decimal import Decimal class CustomEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return float(obj) return json.JSONEncoder.default(self,obj) logger = logging.getLogger() logger.setLevel(logging.INFO) dynamodbTableName = 'IoT_table' dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(dynamodbTableName) getMethod = 'GET' def lambda_handler(event, context): logger.info(event) httpMethod = event['httpMethod'] if httpMethod == getMethod: response = getProducts() else: response = buildResponce(404, 'Not Found from the AWS Lambda sir') return response def getProducts(): try: response = table.scan() result = response['Items'] return buildResponce(200, result) except: logger.exception('Do your Custom error handling here. I am just gonna log it out here!!') def buildResponce(statusCode, body=None): responce = { 'statusCode':statusCode, 'headers' : { 'content-Type' : 'application/json', 'Access-control-Allow-Origin':'*' } } if body is not None: responce['body'] = json.dumps(body, cls=CustomEncoder) print(responce) return responce</span> |
Go to the AWS API Gateway console by searching API Gateway in the AWS console’s search box. Click the Create API option to build a new API Gateway.
Select the REST API option and click Build.
Choose REST as the protocol and the New API option in the Create New API section, then enter IoT_api as the API name. Create an API by clicking create API the button.
After creating an API, you will need to create a method. To do so, go to Actions and then to the Create Method option on the Actions blade.
We need the GET method, so choose that and click the true option next.
Select Lambda Function as the integration type and select the Use Lambda Proxy integration option. Enter and pick the previously generated lambda function, then save the modifications.
To use this API, we must first create a Resource. To do so, go to the Actions blade, click Create Resource, and then input the Resource Name IOT_API_RESOURCE. After checking the CORS box, select the Create Resource option.
After building the method and resources, we must deploy them. To do so, go to Actions and select Deploy API from the Actions blade.
Select Deployment stage as New Stage. After that, enter the Stage name as IOT_API_stagr, then click the Deploy.
API is deployed and the URL will be displayed. Make note of the Invoked URL which we will use in the testing section.
Select the GET method in the POSTMAN software, paste the previously copied URL into the params section, and click send. We will soon be able to see DynamoDB data in the Body section and the 200 OK status code.
Amazon API Gateway allows you to create, deploy, manage, audit, and secure APIs. As a result, the API Gateway facilitates the creation of APIs for IoT applications and other web and mobile applications. API gateway helps to create HTTP, RESTful, and WebSocket APIs. These will be used based on the customer application use cases.
CloudThat is the official AWS Advanced Consulting Partner, Microsoft Gold Partner, and Training partner helping people develop knowledge on the cloud and help their businesses aim for higher goals using best in industry cloud computing practices and expertise. We are on a mission to build a robust cloud computing ecosystem by disseminating knowledge on technological intricacies within the cloud space. Our blogs, webinars, case studies, and white papers enable all the stakeholders in the cloud computing sphere.
If you have any queries about Amazon MQ setup with Java Application, Amazon Messaging Broker, or any other AWS services, feel free to drop in a comment and we will get back to you quickly.
Ans: API Gateway is a fully managed service by AWS that allows developers to create, deploy, manage, audit, and secure APIs at any scale.
Ans: API Gateway supports HTTP, REST, and WebSocket APIs.
Voiced by Amazon Polly |
Vasanth Kumar R works as a Sr. Research Associate at CloudThat. He is highly focused and passionate about learning new cutting-edge technologies including Cloud Computing, AI/ML & IoT/IIOT. He has experience with AWS and Azure Cloud Services, Embedded Software, and IoT/IIOT Development, and also worked with various sensors and actuators as well as electrical panels for Greenhouse Automation.
Our support doesn't end here. We have monthly newsletters, study guides, practice questions, and more to assist you in upgrading your cloud career. Subscribe to get them all!
Click to Comment