top of page

Tutorial to build a CRUD API with Lambda and DynamoDB

Learning Objectives: -:

  • Learn to create an HTTP API using the API Gateway.

  • Learn to create a DynamoDB table & perform CRUD operations.

  • Learn to create a Lambda function.


Step 1: In AWS management console, go to DynamoDB service.

Choose Create table.

For Table name, enter http-crud-tutorial-items.

For Partition key, enter id.

Choose Create table.

Step 2: In AWS management console, go to Lambda console.

Choose Create function.

For Function name, enter http-crud-tutorial-function.

Under Permissions choose Change default execution role.

Select Create a new role from AWS policy templates.

For Role name, enter http-crud-tutorial-role.

For Policy templates, choose Simple microservice permissions. This policy grants the Lambda function permission to interact with DynamoDB.

Choose Create function.

Open index.mjs in the console's code editor and replace its contents with the following code. Choose Deploy to update your function.

import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

import {

DynamoDBDocumentClient,

ScanCommand,

PutCommand,

GetCommand,

DeleteCommand,

} from "@aws-sdk/lib-dynamodb";


const client = new DynamoDBClient({});


const dynamo = DynamoDBDocumentClient.from(client);


const tableName = "http-crud-tutorial-items";


export const 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.send(

new DeleteCommand({

TableName: tableName,

Key: {

id: event.pathParameters.id,

},

})

);

body = `Deleted item ${event.pathParameters.id}`;

break;

case "GET /items/{id}":

body = await dynamo.send(

new GetCommand({

TableName: tableName,

Key: {

id: event.pathParameters.id,

},

})

);

body = body.Item;

break;

case "GET /items":

body = await dynamo.send(

new ScanCommand({ TableName: tableName })

);

body = body.Items;

break;

case "PUT /items":

let requestJSON = JSON.parse(event.body);

await dynamo.send(

new PutCommand({

TableName: tableName,

Item: {

id: requestJSON.id,

price: requestJSON.price,

name: requestJSON.name,

},

})

);

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: In AWS management console, go to API gateway.

Choose Create API, and then for HTTP API, choose Build.

For API name, enter http-crud-tutorial-api.

For Configure routes, choose Next to skip route creation. You create routes later.

Review the stage that API Gateway creates for you, and then choose Next.

Choose Create.

Step 4:

1. Choose your API.

2. Choose Routes.

3. Choose Create.

4. For Method, choose GET.

5. For the path, enter /items/{id}. The {id} at the end of the path is a path parameter that API Gateway retrieves from the request path when a client makes a request.

6. Choose Create.

Repeat steps 4-6 for GET /items, DELETE /items/{id}, and PUT /items

Step 5: Choose your API.

Choose Integrations.

Choose Manage integrations and then choose Create.

Skip Attach this integration to a route. You complete that in a later step.

For Integration type, choose Lambda function.

For Lambda function, enter http-crud-tutorial-function.

Choose Create.

Step 6:

1. Choose your API.

2. Choose Integrations.

3. Choose a route.

4. Under Choose an existing integration, choose http-crud-tutorial-function.

5. Choose Attach integration.

6. Repeat steps 4-5 for all routes.

All routes show that an AWS Lambda integration is attached.

Step 7: Choose your API.

Note your API's invoke URL. It appears under Invoke URL on the Details page.

Copy your API's invoke URL.

To create or update an item

Use the following command to create or update an item. The command includes a request body with the item's ID, price, and name.

curl -X "PUT" -H "Content-Type: application/json" -d "{\"id\": \"123\", \"price\": 12345, \"name\": \"myitem\"}" https://abcdef123.execute-api.us-west-2.amazonaws.com/items

To get all items

  • Use the following command to list all items.

To get an item

  • Use the following command to get an item by its ID.

To delete an item

  1. Use the following command to delete an item.

2. Get all items to verify that the item was deleted.

Note: Delete DyanamoDB Table, API Gateway and Lambda function if no longer in use.


Was this document helpful? How can we make this document better. Please provide your insights. You can download PDF version for reference.


Crud_API
.pdf
Download PDF • 1.12MB

For your aws certification needs or for aws learning contact us.



13 Comments


Very useful sir

Like

Easy to understand

Like

Easy to understand sir

Like

Gokulnath
Gokulnath
Feb 29

Good blog

Like

Atchaya B
Atchaya B
Feb 29

Useful blog sir

Like
bottom of page