Serverless REST APIs with API Gateway, Lambda and DynamoDB
The most common serverless backend is API Gateway → Lambda → DynamoDB: no servers, automatic scaling, pay per request.
flowchart LR
C["Client (browser / app / curl)"] -->|"HTTPS POST /products"| G["API Gateway HTTP API<br/>routes · CORS · auth · throttling"]
G -->|"event (payload 2.0)"| L["Lambda products-api"]
L -->|"PutCommand / GetCommand / Scan"| D[("DynamoDB Products")]
L -->|"{statusCode, headers, body}"| G --> C
HTTP API vs REST API
| HTTP API | REST API | |
|---|---|---|
| Price / latency | Cheaper, faster | More expensive |
| Features | Routes, Lambda/HTTP integrations, JWT/Lambda authorisers, CORS | + API keys & usage plans, request validation, transformation, caching, WAF, private APIs |
| Use when | Most Lambda backends | You need the extra features |
Routes and integrations
- A route = method + path:
GET /products,POST /products,GET /products/{id},ANY /{proxy+},$default. - A Lambda proxy integration passes the whole request as the event and expects a response object.
The event your function receives (payload 2.0)
{
"version": "2.0",
"routeKey": "GET /products/{id}",
"rawPath": "/products/p-1",
"pathParameters": { "id": "p-1" },
"queryStringParameters": { "fields": "name" },
"headers": { "content-type": "application/json" },
"body": null,
"requestContext": { "http": { "method": "GET", "sourceIp": "49.36.112.18" }, "stage": "$default" }
}
The response your function returns
return { statusCode: 201, headers: { 'content-type': 'application/json' }, body: JSON.stringify(item) };
A plain object return is turned into 200 with a JSON body. An unhandled error gives the client 500 Internal Server Error – log the details, return clean messages.
A complete handler
const json = (statusCode, body) => ({ statusCode, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
export const handler = async ({ routeKey, pathParameters, body }) => {
if (routeKey === 'GET /products') return json(200, (await db.send(new ScanCommand({ TableName: TABLE }))).Items);
if (routeKey === 'GET /products/{id}') {
const r = await db.send(new GetCommand({ TableName: TABLE, Key: { id: pathParameters.id } }));
return r.Item ? json(200, r.Item) : json(404, { message: 'Product not found' });
}
if (routeKey === 'POST /products') {
const item = { id: randomUUID(), ...JSON.parse(body || '{}') };
await db.send(new PutCommand({ TableName: TABLE, Item: item }));
return json(201, item);
}
return json(400, { message: `Unsupported route ${routeKey}` });
};
Stages, security and limits
| Topic | Notes |
|---|---|
| Stages | $default (served at the root) or named (/prod), auto-deploy option |
| CORS | Configure on the API so browsers on other origins can call it |
| Authorisation | IAM, JWT authoriser (Cognito, Auth0), Lambda authoriser |
| Throttling | Rate and burst limits per stage/route – protects your backend |
| Permissions | API Gateway needs a Lambda resource policy (added automatically by the console) |
| Timeouts | Integration timeout 30 s (HTTP API) |
| Custom domain | api.example.com with an ACM certificate |
The execution role must allow the DynamoDB actions your code calls – the classic first error is AccessDeniedException … dynamodb:PutItem. Grant exactly those actions on the table ARN.
Practise it
Virtual lab · Amazon Web Services · 45 min
Build a serverless REST API: API Gateway + Lambda + DynamoDB
Build the most common serverless backend in the industry: a Products API with an HTTP API front door, a Lambda function using the AWS SDK v3, and a DynamoDB table – and fix a real AccessDenied error with least-privilege IAM.
Quick revision
- HTTP APIs suit most Lambda backends; REST APIs add advanced features.
- Routes = method + path;
{id}→event.pathParameters.id. - Return
{statusCode, headers, body}(body is a string). - CORS, JWT authorisers and throttling are configured on the API.
- Least-privilege execution role for DynamoDB actions.
Practise this topic
Hands-on virtual lab
Apply what you just read in a realistic, guided simulation. Free with a verified account.
Create a free account to track your progress and unlock virtual labs.