← Learning Hub
Intermediate

Build a Serverless API: API Gateway + Lambda + DynamoDB

A complete back end with no servers to manage: API Gateway receives the HTTP request, a Lambda function runs your code, and DynamoDB stores the data. You pay per request.

This is a complete back end without any server to look after. Each piece does one job and scales by itself: API Gateway receives requests, Lambda runs your code only when called, and DynamoDB stores data. For small and medium apps it can cost almost nothing when traffic is low, which makes it popular with start-ups and side projects.

The Lambda function (Python)

Example
import json, os, uuid
import boto3

table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])

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

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

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

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

Wire it up

  • DynamoDB: create a table Products with partition key id (String), on-demand capacity.
  • Lambda: create a Python function, paste the code, and add the environment variable TABLE_NAME=Products.
  • IAM: give the function's role permission for dynamodb:PutItem and dynamodb:Scan on that one table only.
  • API Gateway: create an HTTP API with routes GET /products and POST /products, both pointing to the Lambda. Turn on CORS for your website's address.
Example
curl -X POST https://abc123.execute-api.ap-south-1.amazonaws.com/products \
     -H "Content-Type: application/json" -d '{"name": "Pen", "price": 20}'

curl https://abc123.execute-api.ap-south-1.amazonaws.com/products
scan reads the whole table - fine for learning, slow and costly for big tables. Real apps design keys so they can use query instead.
For a single function you can also use a Lambda function URL: a direct HTTPS address without API Gateway.
Key points
  • API Gateway -> Lambda -> DynamoDB is a classic serverless stack.
  • The Lambda reads the request and returns status, headers and body.
  • Use query with good keys instead of scan for big tables.

📝 Test yourself

1. Which service gives the Lambda a public HTTPS address with routes?
2. What permissions should the Lambda role have?
3. Fill in the DynamoDB method that saves one item:
table.(Item=item)