URL shortener

Create DynamoDB Table

Table name: UrlShortener

Partition key: shortCode (string)

Lambda Function 1: Create Short URL

Name: CreateShortUrl

import json
import boto3
import string
import random

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('UrlShortener')

def generate_short_code(length=6):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def lambda_handler(event, context):
    body = json.loads(event['body'])
    long_url = body.get('long_url')

    if not long_url:
        return {
            "statusCode": 400,
            "body": json.dumps({"error": "Missing URL"})
        }

    short_code = generate_short_code()
    table.put_item(Item={
        "shortCode": short_code,
        "longUrl": long_url
    })

    return {
        "statusCode": 200,
        "body": json.dumps({
            "short_url": f"https://your-api-id.amazonaws.com/{short_code}"
        })
    }
Lambda Function 2: Redirect

Name: RedirectToOriginal

import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('UrlShortener')

def lambda_handler(event, context):
    short_code = event['pathParameters']['code']

    response = table.get_item(Key={'shortCode': short_code})
    if 'Item' in response:
        long_url = response['Item']['longUrl']
        return {
            "statusCode": 301,
            "headers": {
                "Location": long_url
            }
        }
    else:
        return {
            "statusCode": 404,
            "body": "URL not found"
        }
Create API Gateway

POST /shorten → CreateShortUrl Lambda

GET /{code} → RedirectToOriginal Lambda

Don’t forget to:

  • Enable CORS on both endpoints (especially for POST)
  • In the API Gateway console, go to your API → Resources → click on the method (POST or GET) → click Actions → select Enable CORS. Confirm the settings and click Enable CORS and replace existing CORS headers, then Deploy the API afterward.

  • Deploy to a stage (e.g., prod)
  • In the API Gateway console, click Actions → Deploy API → choose an existing stage or create a new one (e.g., prod) → click Deploy. This will generate the live endpoint URL you can use in your frontend.

  • Replace your-api-id in the code with your actual API Gateway URL
Create Frontend (HTML Form on S3)
<!DOCTYPE html>
<html>
<head><title>Shorten URL</title></head>
<body>
  <form onsubmit="shortenUrl(); return false;">
    <input id="longUrl" placeholder="Paste your long URL" size="50">
    <button type="submit">Shorten</button>
  </form>
  <p id="result"></p>

  <script>
    async function shortenUrl() {
      const longUrl = document.getElementById("longUrl").value;
      const res = await fetch("https://your-api-id.amazonaws.com/shorten", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ long_url: longUrl })
      });
      const data = await res.json();
      document.getElementById("result").innerHTML = `<a href="${data.short_url}" target="_blank">${data.short_url}</a>`;
    }
  </script>
</body>
</html>

Host this file in S3 (see bookmark project part "Build the Frontend" for a detailed explanation on how to use S3 to store a static website).