Build a Node Js CRUD API with AWS Lambda function and DynamoDB

Build a Node Js CRUD API with AWS Lambda function and DynamoDB

?? Thank you for your interest in this article, if you like the content feel free to follow me, clap???? and share it.??

Table of Contents

  1. Create a DynamoDB table
  2. Create a Lambda function
  3. Create an HTTP API
  4. Create routes
  5. Create an integration
  6. Attach your integration to routes
  7. Deploy API’s
  8. Test your API

1. Create a DynamoDB table

You use a DynamoDB table to store data for your API.

Each user has a unique ID, which we use as the partition key for the table.

To create a DynamoDB table

  1. Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
  2. Choose Create table.
  3. For Table name, enter http-crud-users.
  4. For Partition key, enter userId.
  5. Choose Create table.

2. Create a Lambda function

You create a Lambda function for the backend of your API. This Lambda function creates, reads, updates, and deletes users from DynamoDB. The function uses events from API Gateway to determine how to interact with DynamoDB. For simplicity, this tutorial uses a single Lambda function. As a best practice, you should create separate functions for each route.

To create a Lambda function

  1. Sign in to the Lambda console at https://console.aws.amazon.com/lambda.
  2. Choose Create function.
  3. For Function name, enter http-crud-users-function.
  4. For Runtime, choose either the latest supported Node.js or Python runtime.
  5. Under Permissions choose Change default execution role.
  6. Select Create a new role from AWS policy templates.
  7. For Role name, enter http-crud-users-role.
  8. For Policy templates, choose Simple microservice permissions. This policy grants the Lambda function permission to interact with DynamoDB.
  9. Choose Create function.
  10. Open the Lambda function 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-users";

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

  try {
    switch (event.routeKey) {
      case "DELETE /users/{userId}":
        await dynamo.send(
          new DeleteCommand({
            TableName: tableName,
            Key: {
              userId: event.pathParameters.userId,
            },
          })
        );
        body = `Deleted user ${event.pathParameters.userId}`;
        break;
      case "GET /users/{userId}":
        body = await dynamo.send(
          new GetCommand({
            TableName: tableName,
            Key: {
              id: event.pathParameters.userId,
            },
          })
        );
        body = body.user;
        break;
      case "GET /users":
        body = await dynamo.send(
          new ScanCommand({ TableName: tableName })
        );
        body = body.users;
        break;
      case "PUT /users":
        let requestJSON = JSON.parse(event.body);
        await dynamo.send(
          new PutCommand({
            TableName: tableName,
            user: {
              userId: requestJSON.userId,
              price: requestJSON.price,
              name: requestJSON.name,
            },
          })
        );
        body = `Put user ${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,
  };
};        

3. Create an HTTP API

The HTTP API provides an HTTP endpoint for your Lambda function. In this step, you create an empty API. In the following steps, you configure routes and integrations to connect your API and your Lambda function.

To create an HTTP API

  1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
  2. Choose Create API, and then for HTTP API, choose Build.
  3. For API name, enter http-crud-users-api.
  4. Choose Next.
  5. For Configure routes, choose Next to skip route creation. You create routes later.
  6. Disable Auto deploy Review the stage that API Gateway creates for you, and then choose Next.
  7. Choose Create.

4. Create routes

Routes are a way to send incoming API requests to backend resources. Routes consist of two parts: an HTTP method and a resource path, for example, GET /users. For this example API, we create four routes:

  • GET /users/{id}
  • GET /users
  • PUT /users
  • DELETE /users/{id}

To create routes

  1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
  2. Choose your API.
  3. Choose Routes.
  4. Choose Create.
  5. For Method, choose GET.
  6. For the path, enter /users/{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.
  7. Choose Create.
  8. Repeat steps 4–7 for GET /users, DELETE /users/{id}, and PUT /users.

5. Create an integration

You create an integration to connect a route to backend resources. For this example API, you create one Lambda integration that you use for all routes.

To create an integration

  1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
  2. Choose your API.
  3. Choose Integrations.
  4. Choose Manage integrations and then choose Create.
  5. Skip Attach this integration to a route. You complete that in a later step.
  6. For Integration type, choose Lambda function.
  7. For Lambda function, enter http-crud-users-function.
  8. Choose Create.

6. Attach your integration to routes

For this example API, you use the same Lambda integration for all routes. After you attach the integration to all of the API’s routes, your Lambda function is invoked when a client calls any of your routes.

To attach integrations to routes

  1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
  2. Choose your API.
  3. Choose Integrations.
  4. Choose a route.
  5. Under Choose an existing integration, choose http-crud-users-function.
  6. Choose Attach integration.
  7. Repeat steps 4–6 for all routes.

All routes show that an AWS Lambda integration is attached.

7. Deploy API’s

  1. Click on the “Deploy” button
  2. Select the desired stage (e.g., “default”).
  3. Click “Deploy” to deploy all API resources.
  4. Your API is now live and ready for testing.

8. Test your API

To get the URL to invoke your API

  1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
  2. Choose your API.
  3. Note your API’s invoke URL. It appears under Invoke URL on the Details page.
  4. Copy your API’s invoke URL.
  5. The full URL looks like https://abcdef123.execute-api.us-west-2.amazonaws.com.

To create or update an user

  • Use the following command to create or update an user. The command includes a request body with the user’sID, price, and name.
  • curl -X "PUT" -H "Content-Type: application/json" -d "{\"id\": \"123\", \"price\": 12345, \"name\": \"myUser\"}" https://abcdef123.execute-api.us-west-2.amazonaws.com/users

To get all users

  • Use the following command to list all users
  • curl https://abcdef123.execute-api.us-west-2.amazonaws.com/users

To get an user

  • Use the following command to get an user by its ID.
  • curl https://abcdef123.execute-api.us-west-2.amazonaws.com/users/123

To delete an user

  1. Use the following command to delete an user.

  • curl -X "DELETE" https://abcdef123.execute-api.us-west-2.amazonaws.com/users/123

  1. Get all users to verify that the user was deleted.

  • curl https://abcdef123.execute-ap

?? Thank you for reading my article, if you like the content feel free to , clap follow me???? and share it.??


Mallikarjuna Sharma

Js Full Stacker , AWS Architect , Scrum Master , GraphQl associate

4 个月

i am not sure how many people have actually tested it .. All the steps are proper but this wont work directly unless we update lambda with ?????? Item : { ???????userid: requestJSON.userid, ???????price: requestJSON.price, ???????name: requestJSON.name, ??????} userid should be smallcase as mentioned in Partition id

RAVVA PAVAN KUMAR RAJU

ASSOCIATE SOFTWARE ENGINEER| AHEX TECHNOLOGIES| BE-CSE-RCET-21' GRADUATE

5 个月

Helpful !

Gaurav Katwate

MSC (Computer Science) Pune Vidyarthi Griha, Pune.

5 个月

Very helpful!

Prathamesh Dongale

Frontend Developer at Vishwa Technologies Karad

5 个月

Very helpful!

Harish Palsande

Software Engineer | Full Stack Developer | React Js | Node Js | Microservices | AWS | Azure | Architecture

5 个月

Hi! I thought you might like to read my new article: Build a Node Js CRUD API with AWS Lambda function and DynamoDB https://www.dhirubhai.net/pulse/build-node-js-crud-api-aws-lambda-function-dynamodb-harish-palsande-zjpic

要查看或添加评论,请登录

社区洞察

其他会员也浏览了