Planning serverless API
The user wants to create a serverless API using AWS Lambda and DynamoDB, and they seem to be looking for a tutorial-style walkthrough. This means I should include things like infrastructure design, Lambda function coding (likely in Node.js or Python), API Gateway, and DynamoDB setup. I should also consider IAM roles, error handling patterns, and several best practices. I think I'll go with AWS SAM and provide a YAML example, along with console-based steps and Lambda code.Structuring serverless API tutorial
I want to provide a clear structure for the serverless API tutorial. I'll include high-level architecture, DynamoDB table schema, and Lambda function code for basic CRUD operations. It's important to map API Gateway integration and handle errors in Lambda through input validation, try/catch around DynamoDB calls, and proper HTTP status codes. I should show example IAM role policies and possibly include sample request/response. I think using Node.js 18.x with AWS SDK v2 will keep things simpler for now.Focusing on error handling
I need to emphasize proper error handling in the API, including custom error classes like ValidationError and NotFoundError, with appropriate status codes and ensuring that unhandled errors return a 500 status. I might suggest using structured logging too. For the API, I could propose a simple "Todo" structure with endpoints for creating, retrieving, updating, and deleting items. I can choose to implement a single Lambda function handling multiple routes based on event.httpMethod and path. I will provide a minimal AWS SAM template to manage the infrastructure effectively.Creating structured tutorial
I want to keep my response concise, especially since I need to meet verbosity level 2. I’ll structure the tutorial like this:
- A brief summary of the architecture,
- Definition of the DynamoDB table and its primary key,
- Lambda function code in Node.js that includes error handling,
- An Infrastructure as Code (IaC) snippet using AWS SAM, or guidance on using the AWS console,
- Suggestions for testing and potential improvements.
This way, I can deliver clear, actionable information without being too wordy!Designing serverless API
I'm sketching out a Node.js Lambda function for an API with proper error handling. The key components include importing AWS SDK, defining HTTP error classes, and setting up a response function. My plan is to create a minimal CRUD API for handling items, with endpoints like POST, GET, PUT, and DELETE.
I’ll present a simple AWS SAM template to set up DynamoDB and API Gateway alongside Lambda. I want to keep explanations concise while ensuring clear guidance on connecting everything together. It’s essential to highlight error handling and utilize environment variables properly for DynamoDB access.Implementing route handlers
In my handler, I’m routing based on the event resource and HTTP method. For instance, I will create items with a POST request at /items and retrieve them using a GET request at /items/{id}.
While I could have a separate function for each operation, I think it’s clearer to consolidate logic into one function initially for simplicity. I’ll implement core CRUD operations on items, ensuring robust error handling, and I'll clarify how to connect everything through API Gateway.
I’ll keep the error handling consistent and provide clear JSON responses. That way, it’ll be easy for the user to adapt!Structuring the Lambda handler
I’m finalizing the main handler for the Lambda function, where I’m logging useful request details while avoiding sensitive information. I’ll use structured error handling: if an unsupported route is hit, I’ll throw a 404 error. My catch block will log errors with details but won’t expose internal information to the client. I must also mention enabling CloudWatch logs and alarms for monitoring.
Next, I’m thinking about how to create the DynamoDB table and configure the API Gateway efficiently while emphasizing proper error handling methods. Overall, I want to keep this concise and clear for the user. Below is a complete, minimal pattern for a serverless REST API on AWS using:
- API Gateway (REST, Lambda proxy)
- AWS Lambda (Node.js)
- DynamoDB
- With structured error handling and proper HTTP status codes
1. Create the DynamoDB table
Using AWS CLI (you can also do this via the Console):
aws dynamodb create-table \
--table-name Items \
--attribute-definitions AttributeName=id,AttributeType=S \
--key-schema AttributeName=id,KeyType=HASH \
--billing-mode PAY_PER_REQUEST
This creates a table Items with primary key id (string).
2. Lambda function with proper error handling
Runtime: Node.js 18.x
Handler: index.handler
Environment variable: TABLE_NAME=Items
index.js:
const AWS = require('aws-sdk');
const crypto = require('crypto');
const dynamo = new AWS.DynamoDB.DocumentClient();
const TABLE_NAME = process.env.TABLE_NAME;
// ----- Error & response helpers -----
class HttpError extends Error {
constructor(statusCode, message, details) {
super(message);
this.statusCode = statusCode;
this.details = details;
}
}
const jsonResponse = (statusCode, body) => ({
statusCode,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body ?? {})
});
const parseBody = (body) => {
if (!body) return {};
try {
return JSON.parse(body);
} catch {
throw new HttpError(400, 'Request body must be valid JSON');
}
};
// ----- Route handlers -----
async function handleCreate(event) {
const data = parseBody(event.body);
if (!data.name || typeof data.name !== 'string') {
throw new HttpError(400, '"name" is required and must be a string');
}
const now = new Date().toISOString();
const item = {
id: crypto.randomUUID(),
name: data.name,
createdAt: now,
updatedAt: now
};
try {
await dynamo.put({
TableName: TABLE_NAME,
Item: item,
ConditionExpression: 'attribute_not_exists(id)' // safety
}).promise();
} catch (err) {
if (err.code === 'ConditionalCheckFailedException') {
throw new HttpError(409, 'Item with this id already exists');
}
// Map capacity / throttling errors if you want:
if (err.code === 'ProvisionedThroughputExceededException' || err.code === 'ThrottlingException') {
throw new HttpError(503, 'Service temporarily unavailable');
}
throw err;
}
return jsonResponse(201, item);
}
async function handleGet(event) {
const id = event.pathParameters && event.pathParameters.id;
if (!id) {
throw new HttpError(400, '"id" path parameter is required');
}
let result;
try {
result = await dynamo.get({
TableName: TABLE_NAME,
Key: { id }
}).promise();
} catch (err) {
throw err; // generic 500 handler will cover this
}
if (!result.Item) {
throw new HttpError(404, 'Item not found');
}
return jsonResponse(200, result.Item);
}
async function handleUpdate(event) {
const id = event.pathParameters && event.pathParameters.id;
if (!id) {
throw new HttpError(400, '"id" path parameter is required');
}
const data = parseBody(event.body);
if (!data.name || typeof data.name !== 'string') {
throw new HttpError(400, '"name" is required and must be a string');
}
const now = new Date().toISOString();
let result;
try {
result = await dynamo.update({
TableName: TABLE_NAME,
Key: { id },
UpdateExpression: 'SET #name = :name, updatedAt = :updatedAt',
ExpressionAttributeNames: {
'#name': 'name'
},
ExpressionAttributeValues: {
':name': data.name,
':updatedAt': now
},
ConditionExpression: 'attribute_exists(id)',
ReturnValues: 'ALL_NEW'
}).promise();
} catch (err) {
if (err.code === 'ConditionalCheckFailedException') {
throw new HttpError(404, 'Item not found');
}
throw err;
}
return jsonResponse(200, result.Attributes);
}
async function handleDelete(event) {
const id = event.pathParameters && event.pathParameters.id;
if (!id) {
throw new HttpError(400, '"id" path parameter is required');
}
try {
await dynamo.delete({
TableName: TABLE_NAME,
Key: { id },
ConditionExpression: 'attribute_exists(id)'
}).promise();
} catch (err) {
if (err.code === 'ConditionalCheckFailedException') {
throw new HttpError(404, 'Item not found');
}
throw err;
}
return jsonResponse(200, { deleted: true });
}
// ----- Main Lambda handler with routing & centralized error handling -----
exports.handler = async (event) => {
// Basic structured logging (avoid logging full body in production if it may contain sensitive data)
console.log('Incoming request:', JSON.stringify({
resource: event.resource,
path: event.path,
httpMethod: event.httpMethod,
pathParameters: event.pathParameters,
queryStringParameters: event.queryStringParameters
}));
try {
const { resource, httpMethod } = event;
// Route: POST /items
if (resource === '/items' && httpMethod === 'POST') {
return await handleCreate(event);
}
// Routes on /items/{id}
if (resource === '/items/{id}') {
if (httpMethod === 'GET') return await handleGet(event);
if (httpMethod === 'PUT') return await handleUpdate(event);
if (httpMethod === 'DELETE') return await handleDelete(event);
}
// Unknown route
throw new HttpError(404, 'Route not found');
} catch (err) {
console.error('Error handling request:', {
name: err.name,
message: err.message,
statusCode: err.statusCode,
stack: err.stack
});
if (err instanceof HttpError) {
return jsonResponse(err.statusCode, {
error: err.message,
...(err.details ? { details: err.details } : {})
});
}
// Fallback for unexpected errors
return jsonResponse(500, { error: 'Internal server error' });
}
};
What this gives you:
- Clear validation errors → 400
- Missing items → 404
- Conflict on id (extremely rare here) → 409
- Throttling / capacity (example pattern) → 503
- Unexpected errors → 500, without leaking internal details
3. Wire it up with API Gateway (REST, Lambda proxy)
Using the AWS Console:
-
Create REST API
- API Gateway → Create API → REST API → New API.
-
Create resource /items
- Resources → Actions → Create Resource → Resource Path:
items.
-
Create method POST on /items
- Select
/items → Actions → Create Method → POST.
- Integration type: Lambda Function.
- Check “Use Lambda Proxy integration”.
- Select your Lambda.
-
Create resource /items/{id}
- Select root or
/items → Actions → Create Resource.
- Resource Path:
{id} (so full path becomes /items/{id}).
- Ensure “Configure as proxy resource” is not checked.
-
Create methods on /items/{id}
- For
/items/{id}, create methods:
GET (for handleGet)
PUT (for handleUpdate)
DELETE (for handleDelete)
- All as Lambda Proxy integrations with the same Lambda function.
-
Deploy API
- Actions → Deploy API → New stage, e.g.
dev.
Now your endpoints will be:
POST /items – create
GET /items/{id} – read
PUT /items/{id} – update
DELETE /items/{id} – delete
All backed by DynamoDB with consistent, structured error responses.
4. Optional hardening / improvements
- Enable CloudWatch Logs and alarms on 5xx rates.
- Add API Gateway request validation (JSON schema) to catch bad input before Lambda.
- Use a DLQ (SQS) for failed async invocations, if you use async patterns.
- Add CORS headers if you call this API from a browser.
If you tell me your preferred tools (SAM, CDK, Serverless Framework, Terraform), I can provide an Infrastructure-as-Code template for this exact setup.