This is AWS serverless CRUD API project. In this project, we will create a serverless API that creates, reads, updates, and deletes items from a DynamoDB table. DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability.
When you invoke your HTTP API, API Gateway routes the request to your Lambda function. The Lambda function interacts with DynamoDB, and returns a response to the API Gateway. The API Gateway then returns a response to you.
You use a DynamoDB table to store data for your API.
Each item has a unique ID, which we use as the partition key for the table.
-
Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
-
Click on Create table.
-
For Table name, enter
http-crud-api
. -
For Partition key, enter
id
. -
CLick Create table.
Create a Lambda function for the backend of your API. This Lambda function creates, reads, updates, and deletes items 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.
-
Sign in to the Lambda console at https://console.aws.amazon.com/lambda.
-
Click on Create function.
-
For Function name, enter
http-crud-api-lambda
. -
Under Permissions choose Change default execution role.
-
Select Create a new role from AWS policy templates.
-
For Role name, enter
http-crud-api-project-role
. -
For Policy templates, choose
Simple microservice permissions
. This policy grants the Lambda function permission to interact with DynamoDB. -
Click on Create function.
-
On the console's code editor, replace the code with the following code. and Click on 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-api"
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,
}
}
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.
-
Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
-
Click on the Create API, and then for HTTP API, choose Build.
-
For API name, enter
http-crud-api
. -
Click on Next.
-
For Configure routes, Click on Next to skip route creation. You create routes later.
-
Review the stage that API Gateway creates for you, and then choose Next.
-
Click on Create.
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 /items. For this example API, we create four routes:
-
GET /items/{id}
-
GET /items
-
PUT /items
-
DELETE /items/{id}
-
Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
-
Click on your API.
-
Choose Routes.
-
Choose Create.
-
For Method, choose GET.
-
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. -
Choose Create.
-
Repeat steps 4-7 for
GET /items
,DELETE /items/{id}
, andPUT /items
.
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.
-
Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
-
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-api-lambda
. -
Click on Create.
-
Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
-
Choose your API.
-
Choose Integrations.
-
Choose a route.
-
Under Choose an existing integration, choose
http-crud-api-lambda
. -
Click on Attach integration.
-
Repeat steps 4-6 for all routes. All routes show that an AWS Lambda integration is attached.
-
Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
-
Choose your API.
-
Note your API's invoke URL. It appears under Invoke URL on the Details page.
-
Copy your API's invoke URL.
The full URL looks like
https://abcdef123.execute-api.us-west-2.amazonaws.com
.
- 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
- Use the following command to list all items.
curl https://abcdef123.execute-api.us-west-2.amazonaws.com/items
- Use the following command to get an item by its ID.
curl https://abcdef123.execute-api.us-west-2.amazonaws.com/items/123
- Use the following command to delete an item.
curl -X "DELETE" https://abcdef123.execute-api.us-west-2.amazonaws.com/items/123
- Get all items to verify that the item was deleted.
curl https://abcdef123.execute-api.us-west-2.amazonaws.com/items
- Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
- Select your table.
- Choose Delete table.
- Confirm your choice, and choose Delete.
- Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
- On the APIs page, select an API. Choose Actions, and then choose Delete.
- Choose Delete.
- Sign in to the Lambda console at https://console.aws.amazon.com/lambda.
- On the Functions page, select a function. Choose Actions, and then choose Delete.
- Choose Delete.
- In the Amazon CloudWatch console, open the Log groups page.
- On the Log groups page, select the function's log group
(/aws/lambda/http-crud-api-lambda)
. Choose Actions, and then choose Delete log group. - Choose Delete.
- In the AWS Identity and Access Management console, open the Roles page.
- Select the function's role, for example,
http-crud-api-project-role
. - Choose Delete role.
- Choose Yes, delete.