Create a serverless API that interacts with an AWS DynamoDB table
Tags: tutorial, api, aws
Published: 2023-06-26 23:13:10

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxp5qwcvnptsh3d75s8p.png)

**Create a DynamoDB table

- Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
- Choose Create table.
- For Table name, enter http-crud-tutorial-items.
- For Partition key, enter id.
- Choose Create 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,
  };
};

```

- 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**
- Visit https://console.aws.amazon.com/apigateway
- Choose our API
- Take note of the API's invoke URL, and copy it for later. 

- Test creating or update an item 
```
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

```

- Test getting ALL items
```
curl https://abc123.execute-api.us-east-1.amazonaws.com/items
```
 
- Test getting an item
```
curl https://abc123.execute-api.us-east-1.amazonaws.com/items/123
```

Test deleting an item
```
curl -X "DELETE" https://abc123.execute-api.us-east-1.amazonaws.com/items/123
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hbbty2grl816eiickq51.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nhu0xwh3xurog0lxb3qb.png)