DEV Community

Michael Wahl for AWS Community Builders

Posted on

Create a serverless API that interacts with an AWS DynamoDB table

When we call the API, our request is routed to a Lambda function, which performs the desired action between Lambda and DynamoDB.

Image description

**Create a DynamoDB table

Create a Lambda function

  • Sign in to the Lambda console at https://console.aws.amazon.com/lambda
  • Choose Create function.
  • For Function name, enter http-demo-function.
  • Under Permissions choose Change default execution role.
  • Select Create a new role from AWS policy templates.
  • For Role name, enter http-demo-role.
  • For Policy templates, choose Simple microservice permissions.

  • Create function

  • Open the index.mjs under the Code tab, and replace all the code with this sample code.

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 = "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,
  };
};

Enter fullscreen mode Exit fullscreen mode
  • Choose Deploy to update the function.

Create an HTTP API

  • Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
  • Choose Create API, and then for HTTP API, choose Build.
  • For API name, enter http-demo-api.
  • Choose Next.
  • Review the stage that API Gateway, choose Next.
  • Choose Create.

Create Routes

  • Visit https://console.aws.amazon.com/apigateway
  • Choose your API.
  • Choose Routes.
  • Choose Create.
  • For Method, choose GET.
  • For the path, enter /items/{id}.
  • Choose Create.
  • Now you need to repeat steps 4-7 for GET /items, DELETE /items/{id}, and PUT /items.

Create Integration
This is used to connect a route to backend resources.

  • Visit https://console.aws.amazon.com/apigateway
  • Choose your API.
  • Choose Integrations.
  • Choose Manage integrations, choose create.
  • For Integration type, choose Lambda function.
  • For Lambda function, enter http-demo-function.
  • Choose Create.

Attach our integration to routes

  • Visit https://console.aws.amazon.com/apigateway
  • Choose your API.
  • Choose Integrations.
  • Choose a route.
  • Under Choose an existing integration, choose the http-demo-function. Choose Attach integration. Repeat these steps 4-6 for all the routes we created earlier.

Testing our API

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

Enter fullscreen mode Exit fullscreen mode
  • Test getting ALL items
curl https://abc123.execute-api.us-east-1.amazonaws.com/items
Enter fullscreen mode Exit fullscreen mode
  • Test getting an item
curl https://abc123.execute-api.us-east-1.amazonaws.com/items/123
Enter fullscreen mode Exit fullscreen mode

Test deleting an item

curl -X "DELETE" https://abc123.execute-api.us-east-1.amazonaws.com/items/123
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Top comments (0)