Tutorial: Build an HTTP API with Lambda and DynamoDB
In this tutorial you create your first Serverless Framework service and deploy it to AWS: an HTTP API with two endpoints backed by AWS Lambda functions and an Amazon DynamoDB table. POST /customers stores a customer, and GET /customers lists them. At the end you remove everything you deployed.
You will:
- Create the service from a template with the
serverlesscommand. - Deploy the template and call its endpoint.
- Add a DynamoDB table and two Node.js functions that use the AWS SDK for JavaScript v3.
- Deploy again and test the endpoints with
curl. - Remove the service from your AWS account.
For a video walkthrough of creating and deploying a first service, watch the Serverless Framework Getting Started Tutorial.
Prerequisites
- An AWS account. To create one, use the AWS sign-up page. The identity you deploy with needs permission to create the resources in this tutorial; AWS Credentials lists the options.
- Node.js 20 or later and npm, to install the Framework and the AWS SDK clients (install Node.js); the AWS SDK clients this tutorial installs require Node.js 20 or later. The AWS SDK for JavaScript v3 drops support for a Node.js version some months after that version's end of life; on an older Node.js, npm warns about the clients' supported versions, or refuses to install them when
engine-strictis set. The Node.js version on your machine doesn't decide the Lambda runtime;serverless.ymldoes. - A terminal and a web browser on the same machine. Signing in to Serverless Framework and to the AWS Console opens the browser.
curl, to call the API.
Install the Serverless Framework
Install the CLI globally with npm:
npm install -g serverless
npm 12 prints an install-scripts warning that the serverless package's install script was blocked. The CLI still works: the first serverless command downloads the Framework into ~/.serverless/releases/<version>.
Check the installation:
serverless --version
The command prints the installed version (on the first run, after ✔ Installed Serverless Framework v4.46.0):
Serverless ϟ Framework 4.46.0
For proxies, firewalls and other installation options, see Setting up the Serverless Framework.
What is the Serverless Dashboard?
The Serverless Framework Dashboard is the web app that comes with the Framework. Your Serverless Framework account lives there, so the CLI signs you in through it. For a team, it also shows every deployment in one place, stores secrets and parameters, connects AWS accounts as Providers so deploys need no local AWS credentials, and gives metrics, traces, logs and alerts for your functions. This tutorial uses it only to sign in; see Serverless Framework Dashboard for the rest.
Create the service from a template
The serverless command with no arguments creates a service from a template, signs you in and sets up AWS credentials. It prompts for each choice, so it needs an interactive terminal.
-
In a folder without a
serverless.ymlorserverless-compose.ymlfile (in any of their formats, such as.yamlor.ts), run:serverless -
At
Select A Template, chooseAWS / Node.js / HTTP API. -
At
Name Your Project, entercustomers-api. The CLI downloads the template into a newcustomers-apifolder and setsservice: customers-apiin itsserverless.yml. -
The CLI needs a Serverless Framework account or a License Key. If you aren't signed in yet, it asks you to choose: pick
Login/Register(the other choices areGet A License,Enter A License KeyandExplain Licensing Basics; see License keys). Your browser opens the Serverless Framework Dashboard; after you sign in or register, the CLI saves the session in~/.serverlessrc(or~/.config/.serverlessrcwhen only that file exists) and continues. It adds anorgline with your org name toserverless.yml. -
If the CLI asks
Create Or Select An Existing App(it does when you're signed in with an account, not with a License Key), chooseSkip Adding An App. -
If the CLI asks for an
AWS Credentials Set-Up Method, chooseSign in with AWS Console (Recommended)and keep the profile namedefault. Your browser opens the AWS sign-in page; after you sign in, the CLI writes thedefaultprofile to~/.aws/configand caches short-lived credentials in~/.aws/login/cache. The CLI skips this step when it already finds AWS credentials on your machine, or when your org has a default Provider in the Dashboard. To use another AWS profile you already have, add--aws-profile PROFILE_NAMEto each laterserverlesscommand; Which credentials a deploy uses lists every source in order, including the ones that take precedence over--aws-profile.
The CLI ends with the next steps:
Your new Service "customers-api" is ready. Here are next steps:
• Open Service Directory: cd customers-api
• Install Dependencies: npm install (or use another package manager)
• Deploy Your Service: serverless deploy
The template has no package.json, so skip npm install for now. The customers-api folder includes serverless.yml and a handler.js file with one function, hello.
Without an interactive terminal (CI, an AI agent), the serverless command can't prompt. Create the customers-api folder yourself, write the files from Add a DynamoDB table and two functions, and provide the Serverless Framework and AWS credentials as described in Non-interactive use: CI and AI agents.
Deploy the template service
Go into the service folder and deploy:
cd customers-api
serverless deploy
The Framework packages the code, creates an AWS CloudFormation stack named customers-api-dev and prints the endpoint of the HTTP API. The template sets no stage or Region, so without a --stage or --region option the Framework deploys to the dev stage in us-east-1:
Deploying "customers-api" to stage "dev" (us-east-1)
✔ Service deployed to stack customers-api-dev (45s)
endpoint: GET - https://abc123def4.execute-api.us-east-1.amazonaws.com/
functions:
hello: customers-api-dev-hello (1.6 kB)
When the AWS credentials come from a Dashboard Provider, the first line also names the Provider.
To deploy to another stage or Region, add --stage and --region, for example serverless deploy --stage staging --region eu-west-1. The stack is then customers-api-staging. Pass the same options to every later command in this tutorial (serverless deploy, serverless logs, serverless remove); without them, those commands target the dev stage in us-east-1.
Call the endpoint from the output:
curl https://abc123def4.execute-api.us-east-1.amazonaws.com/
The hello function answers:
{ "message": "Go Serverless v4! Your function executed successfully!" }
Add a DynamoDB table and two functions
In the customers-api folder, you replace the template's function with two functions that read and write a DynamoDB table.
-
Delete the template's
handler.jsfile:rm handler.js -
Create
createCustomer.mjs. The function reads a JSON body withnameandemailand stores it in the table:import { DynamoDBClient } from '@aws-sdk/client-dynamodb' import { DynamoDBDocumentClient, PutCommand } from '@aws-sdk/lib-dynamodb' const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({})) export const handler = async (event) => { const body = event.isBase64Encoded ? Buffer.from(event.body ?? '', 'base64').toString('utf8') : (event.body ?? '') let customer try { customer = JSON.parse(body) } catch { return { statusCode: 400, body: JSON.stringify({ error: 'Body must be JSON' }), } } if ( typeof customer?.name !== 'string' || typeof customer?.email !== 'string' || !customer.name || !customer.email ) { return { statusCode: 400, body: JSON.stringify({ error: 'name and email are required' }), } } await ddb.send( new PutCommand({ TableName: process.env.CUSTOMERS_TABLE, Item: { email: customer.email, name: customer.name }, }), ) return { statusCode: 201, body: JSON.stringify({ name: customer.name, email: customer.email }), } }HTTP API passes the request body as a string, base64-encoded when
isBase64Encodedistrue, so the function decodes it only in that case. The table name comes from theCUSTOMERS_TABLEenvironment variable, whichserverless.ymlsets in step 5. -
Create
getCustomers.mjs. The function returns the customers stored in the table:import { DynamoDBClient } from '@aws-sdk/client-dynamodb' import { DynamoDBDocumentClient, ScanCommand } from '@aws-sdk/lib-dynamodb' const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({})) export const handler = async () => { const result = await ddb.send( new ScanCommand({ TableName: process.env.CUSTOMERS_TABLE, ConsistentRead: true, }), ) return { statusCode: 200, body: JSON.stringify({ total: result.Count, items: result.Items.map(({ name, email }) => ({ name, email })), }), } }ConsistentRead: truemakes the scan include every write that finished before it, such as a customer added just before. AScanreturns at most 1 MB of items per call, and this function returns only that first page, sototalanditemscover that page; that holds every customer in this tutorial. For large tables, query by key instead, or read the next pages withLastEvaluatedKey(Scanning tables in DynamoDB). -
Create a
package.jsonin thecustomers-apifolder and install the AWS SDK v3 clients:npm init -y npm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodbWithout its own
package.json, the folder isn't a project for npm: when a parent folder has apackage.jsonornode_modules,npm installinstalls the clients there instead, outside the service.The Framework packages
node_moduleswith your functions, so they run the client versions pinned inpackage.json. -
In
serverless.yml, keep theorgline theserverlesscommand added at the top (and theappline, if there is one), and replace everything below it with:service: customers-api provider: name: aws runtime: nodejs24.x architecture: arm64 environment: CUSTOMERS_TABLE: ${self:service}-customers-${sls:stage} iam: role: statements: - Effect: Allow Action: - dynamodb:PutItem - dynamodb:Scan Resource: !GetAtt CustomersTable.Arn functions: createCustomer: handler: createCustomer.handler events: - httpApi: path: /customers method: post getCustomers: handler: getCustomers.handler events: - httpApi: path: /customers method: get resources: Resources: CustomersTable: Type: AWS::DynamoDB::Table Properties: TableName: ${self:service}-customers-${sls:stage} BillingMode: PAY_PER_REQUEST AttributeDefinitions: - AttributeName: email AttributeType: S KeySchema: - AttributeName: email KeyType: HASH
The new serverless.yml sets up the following:
provider.environmentsetsCUSTOMERS_TABLEon every function in the service.${self:service}and${sls:stage}make the namecustomers-api-customers-devfor thedevstage, so each stage gets its own table.provider.iam.role.statementsadds a policy statement to the IAM role the Framework creates for the service's functions:PutItemandScanon this table only. See IAM permissions for functions.functionsmaps each function to its file and exportedhandler(createCustomer.handleris thehandlerexport ofcreateCustomer.mjs), and eachhttpApievent adds a route to the service's HTTP API. See HTTP API events.resourcesadds the DynamoDB table to the CloudFormation stack, with on-demand billing andemailas the partition key. See AWS infrastructure resources.
To check the file before deploying, run serverless print. It prints the configuration with variables resolved, and a warning if a Framework property is misspelled; properties under custom and the CloudFormation properties under resources aren't checked this way (configuration validation).
Deploy and test the API
Deploy the changes:
serverless deploy
The Framework updates the customers-api-dev stack: it removes the hello function, and adds the table, the two functions and their routes:
Deploying "customers-api" to stage "dev" (us-east-1)
✔ Service deployed to stack customers-api-dev (60s)
endpoints:
POST - https://abc123def4.execute-api.us-east-1.amazonaws.com/customers
GET - https://abc123def4.execute-api.us-east-1.amazonaws.com/customers
functions:
createCustomer: customers-api-dev-createCustomer (2.8 MB)
getCustomers: customers-api-dev-getCustomers (2.8 MB)
Both functions share one deployment package, so they show the same size. Replace the URL in the following commands with the one from your output.
The two routes have no authorization: anyone with the URL can add and list customers, so store only test data in this API. To restrict who can call the routes, add an authorizer, such as a JWT authorizer.
Add a customer:
curl -X POST https://abc123def4.execute-api.us-east-1.amazonaws.com/customers \
-H 'Content-Type: application/json' \
-d '{"name":"Jane Doe","email":"jane@example.com"}'
The createCustomer function returns the stored customer with status 201:
{ "name": "Jane Doe", "email": "jane@example.com" }
List the customers:
curl https://abc123def4.execute-api.us-east-1.amazonaws.com/customers
The getCustomers function returns the table's items:
{ "total": 1, "items": [{ "name": "Jane Doe", "email": "jane@example.com" }] }
To see a function's logs, run serverless logs --function createCustomer. Each later serverless deploy updates the same stack; when nothing changed, the Framework prints No changes to deploy. Deployment skipped.
Remove the service
Warning: serverless remove deletes the customers-api-dev stack, including the DynamoDB table and every customer stored in it.
serverless remove
The Framework deletes the stack and the service's deployment files:
Removing "customers-api" from stage "dev" (us-east-1)
✔ Service customers-api has been successfully removed (30s)
The AWS credentials profile, your Serverless Framework sign-in and the local customers-api folder stay. The shared S3 bucket the Framework uploads deployment files to stays in your account for other services; see Deployment bucket.
Next steps
You built an HTTP API with two Lambda functions and a DynamoDB table, deployed it, tested it and removed it. To continue:
- Serverless Framework concepts: services, functions, events and resources.
- Dev Mode: run your functions locally against live AWS events.
- Deploying: stages, Regions and what a deploy does.
- Examples and tutorials: more templates and examples to start from.