AWS Builder Center
How I Built a Serverless API Using AWS Lambda and API Gateway

How I Built a Serverless API Using AWS Lambda and API Gateway

Step-by-step guide to deploying a REST API with Lambda, API Gateway, and DynamoDB, including cost tips and common mistakes to avoid

Introduction

Managing servers just to run a small API is a hassle. When I started learning AWS, I wanted a way to build an API without worrying about infrastructure. That is where serverless comes in. In this post, I will show how I built a simple REST API using AWS Lambda, API Gateway, and DynamoDB.

What We Are Building

A simple API that stores and retrieves notes:
  • POST /notes to create a note
  • GET /notes to list all notes

Prerequisites

  • An AWS account
  • Basic knowledge of Python
  • Access to the AWS Console

Step 1: Create a DynamoDB Table

  1. Open the DynamoDB console.
  2. Click Create table.
  3. Table name: Notes
  4. Partition key: id (String)
  5. Keep the default settings and click Create table.

Step 2: Create the Lambda Function

  1. Open the Lambda console and click Create function.
  2. Choose Author from scratch.
  3. Name: notesFunction, Runtime: Python 3.12.
  4. Attach DynamoDB access permission to the function's IAM role.
Paste this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import json
import uuid
import boto3

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("Notes")

def lambda_handler(event, context):
method = event["requestContext"]["http"]["method"]

if method == "POST":
body = json.loads(event["body"])
item = {"id": str(uuid.uuid4()), "text": body["text"]}
table.put_item(Item=item)
return {"statusCode": 201, "body": json.dumps(item)}

if method == "GET":
items = table.scan()["Items"]
return {"statusCode": 200, "body": json.dumps(items)}

return {"statusCode": 405, "body": "Method not allowed"}

Step 3: Create the API Gateway

  1. Open API Gateway and create an HTTP API.
  2. Add an integration pointing to notesFunction.
  3. Create routes: GET /notes and POST /notes.
  4. Deploy and copy the Invoke URL.

Step 4: Test the API

1
2
3
curl -X POST https://YOUR_API_URL/notes \
-H "Content-Type: application/json" \
-d '{"text": "My first note"}'
You should get back the created note with a unique id.

Mistakes I Made

MistakeFix
Got "Access Denied" from DynamoDBAdded the missing IAM permission to the Lambda role
Lambda timed outIncreased the timeout from 3s to 10s
500 error on POSTForgot to parse event["body"] with json.loads

Cost

For small projects, this setup stays within the AWS Free Tier. Always check pricing and set a budget alert.

Conclusion and Key

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article