
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 /notesto create a noteGET /notesto list all notes
Prerequisites
- An AWS account
- Basic knowledge of Python
- Access to the AWS Console
Step 1: Create a DynamoDB Table
- Open the DynamoDB console.
- Click Create table.
- Table name:
Notes - Partition key:
id(String) - Keep the default settings and click Create table.
Step 2: Create the Lambda Function
- Open the Lambda console and click Create function.
- Choose Author from scratch.
- Name:
notesFunction, Runtime: Python 3.12. - 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
- Open API Gateway and create an HTTP API.
- Add an integration pointing to
notesFunction. - Create routes:
GET /notesandPOST /notes. - 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
| Mistake | Fix |
|---|---|
| Got "Access Denied" from DynamoDB | Added the missing IAM permission to the Lambda role |
| Lambda timed out | Increased the timeout from 3s to 10s |
| 500 error on POST | Forgot 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
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article