Build no code restful HTTP API with API Gateway and DynamoDB
Most web applications are using Restful APIs to interactive with the backend services. In the TODO application, it's the straight forward to get, update and delete the items from backend database. Amazon DynamoDB is a key-value database, it fits for this scenario with scalability and optimized pay-as-you-go cost. Also Amazon API Gateway has built-in integration with AWS serivces, the restful API can be transformed to the request to DynamoDB APIs. Using this combination you can provide the restful APIs only provisioning AWS resources without writing the CRUD code!
Let's assume the TODO application having below model to represent the TODO items,
1{
2"subject": "my-memo", // some subject of TODO item
3"description": "the great idea", // some description for the TODO item
4"dueDate": 1661926828, // the timestamp of sceonds for the due date of TODO item
5}
Then define below restful APIs for list, fetch, update and delete TODO item/items.
- Create new TODO item
1PUT /todo
- Update a TODO item
1POST /todo/<todo id>
- Delete a TODO item
1DELETE /todo/<todo id>
- List TODO items
1GET /todo
All magic with no code restful API of API Gateway is setting up data transformations for REST API.
Belos is using the Apache VTL to transform the request JSON payload to DynamoDB UpdateItem API request.
Also using API Gateway's transformation feature of the response of integration(DynamoDB API in this case) to shape the response like below,
There are few best practise of using API Gateway and AWS services integration to simplify the CRUD operations,
- use request validator to validate the request payload
- use integration response to handle with the error cases of integration services. Below is an example checking the error message of DynamoDB API then reshape the error message
1#if($input.path('$.__type') == "com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException")
2{
3 "message": "the todo id already exists."
4}
5#end
- sanity all string inputs from client via API Gateway built-in $util method
$util.escapeJavaScript()
to avoid NoSQL injection attack - response valid json if the string contains signle quotes(')
1"subject": "$util.escapeJavaScript($input.path('$.Attributes.subject.S')).replaceAll(\"\\\\'\",\"'\")"
As usual, all AWS resources are orchestrated by AWS CDK project, it's easliy to be deployed to any account and any region of AWS!
Happying 👨💻 API 😆😆😆
Posts in this series
- Build serverless web application with AWS Lambda web adapter
- Define your API via OpenAPI definition on AWS
- Setup DevOps pipeline with few code
- Federated OIDC login with Cognito and Amplify
- Protect website with Cognito
- Distribute the website globally
- Build no code restful HTTP API with API Gateway and DynamoDB
- Build serverless web application with AWS Serverless
- 无服务器架构的Docker镜像数据分析应用
- 无服务器架构的域名重定向服务
- Spring Cloud Function -- 跨Serverless平台的函数计算框架
- 基于函数计算的钉钉回调函数接口