Implementing api gateway with lamda and dynamoDB for CRUD operation

Implementing api gateway with lamda and dynamoDB for CRUD operation

Clock Icon2021.06.18

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Introduction:

I implemented lightweight  http api for performing Create,Read,Update,Delete operation in dynamoDb.

Steps for implementing:

step1: create dynamoDB table with partition key

https://aws.amazon.com/dynamodb/getting-started/

step 2: create a lambda function

i used nodejs for witing function

  •     step a: open lambda from console
  •     step b: click on create function after selecting runtime
  •     step c: write the code as below changing the items and table name
  •     step d: test the code and deploy
  •     step e: attach dynamodb permision to function by configuration>permission.

lambda code(node.js):

const AWS = require("aws-sdk");

const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event, context) => {
let body;
let statusCode = 200;
const headers = {
"Content-Type": "application/json"
};

try {
switch (event.routeKey) {
case "DELETE /items/{id}":
await dynamo
.delete({
TableName: "For-developers-io",
Key: {
uid: event.pathParameters.id
}
})
.promise();
body = `Deleted item ${event.pathParameters.id}`;
break;
case "GET /items/{id}":
body = await dynamo
.get({
TableName: "For-developers-io",
Key: {
uid: event.pathParameters.id
}
})
.promise();
break;
case "GET /items":
body = await dynamo.scan({ TableName: "For-developers-io" }).promise();
break;
//put api
case "PUT /items":
let requestJSON = JSON.parse(event.body);
await dynamo
.put({
TableName: "For-developers-io",
Item: {
//list all the items you want to add in table,

uid: context.awsRequestId,//
}
})
.promise();
body = `Put item ${requestJSON.id}`;
break;
default:
throw new Error(`Unsupported route: "${event.routeKey}"`);
}
} catch (err) {
statusCode = 400;
body = err.message;
} finally {
body = JSON.stringify(body);
}

return {
statusCode,
body,
headers
};
};

 
Step 3: Creat http api using api gateway
  • step a: console open api gateway and choose build in http api
  • step b: write api name and select review and create
  • step c: create routes get for read ,put for create and update ,delete for delete
  • step d: select integration create an integration for all the routes
  • step e: in integration target choose "lambda function" and in integration detail choose the lambda function we created in step 2 for all the routes
  • step f: you get invoke url /api in api details which can be used for any frontend or mobile application

conclusion :

we have successfully created api to perform crud operation using http api(lightweight and economical) from api gateway, lambda and dynamoDB

 

 

 

 

 

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.