
Building a Serverless URLShortener
Sharing long URLs can be a hassle. URL shorteners create unique, shareable links. In this blog, we'll build a serverless URL shortener.
- AWS Lambda to run our URL shortening and redirection logic
- Amazon API Gateway to expose HTTP endpoints for our Lambda functions
- Amazon DynamoDB as a NoSQL database to store the URL mappings
- Terraform for provisioning all the AWS resources
- A client sends a POST request to the API Gateway endpoint with the long URL they want to shorten.
- API Gateway invokes the "create URL" Lambda function.
- The Lambda function generates a unique short ID, stores the mapping (short ID -> long URL) in DynamoDB, and returns the short ID.
- To access the original URL, the client sends a GET request to the API Gateway endpoint with the short ID.
- API Gateway invokes the "get URL" Lambda function.
- The Lambda function looks up the short ID in DynamoDB and returns an HTTP 301 redirect to the original long URL.
- A DynamoDB table to store the URL mappings
- An IAM role and policy to grant Lambda functions access to DynamoDB
- Two Lambda functions: one for creating short URLs, another for retrieving the original URLs
- An API Gateway HTTP API with routes and integrations mapped to the Lambda functions
- It parses the request body to get the original long URL.
- Generates a unique 8-character short ID by hashing the long URL and current timestamp.
- Stores the short ID -> long URL mapping in DynamoDB.
- Returns the short ID in the response.
- Extracts the short ID from the request path parameters.
- Queries DynamoDB for the corresponding long URL.
- If found, returns an HTTP 301 redirect to the long URL.
- If not found, returns a 404 error.
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/very-long-url"}'
{"short_id": "a1b2c3d4"}
.-L
flag in curl follows the HTTP 301 redirect to the long URL.Let us use Amazon Q to help us with the problem statement.


a. tf
b. tf
c. tf
d. tf
e. Lambda
i. Create-url.py
ii. Get-url.py

- Imports Required Libraries
- json : Handles JSON response
- os : Fetches environment variables (DynamoDB table name).
- boto3 : AWS SDK for Python to interact with DynamoDB.
- Key : Helps query DynamoDB items. - Initialize DynamoDB Table
- Reads DYNAMODB_TABLE from environment variables.
- Connects to the DynamoDB table. - Lambda Function ( lambda_handler )
- Extracts short_id from the URL path parameters.
- Queries DynamoDB for the corresponding long_url .
- If found, returns an HTTP 301 redirect to long_url .
- If not found, returns HTTP 404.
- If an error occurs, returns HTTP 500 with the error message.


{ "short_id": "a1b2c3d4" }


Some important notes:-
https://abc123def.execute-api.useast-1.amazonaws.com/prod
Make sure to keep the API endpoint URL for future use
The shortened URLs are stored in DynamoDB and will persist until deleted.
Any opinions in this post are those of the individual author and may not reflect the opinions of AWS.