
I Built a Serverless URL Shortener Using AWS Lambda, API Gateway & DynamoDB ๐ | Complete Hands-On Project
Want to build a real-world AWS project? ๐ In this hands-on tutorial, we'll build a fully serverless URL Shortener using AWS Lambda, API Gateway, and DynamoDB. Learn the architecture, write Python code, configure AWS services, and test your application step by step. Perfect for AWS beginners, cloud enthusiasts, and aspiring DevOps engineers!
๐ Let's Build a Real-World AWS Project!
Have you ever wondered how websites convert long URLs into short links like ย
bit.ly/abc123ย ?Today, we're going to build our own Serverless URL Shortener using AWS!
This isn't just a theoretical project. We'll use real AWS services, write Python code, deploy our application, and test it.
Whether you're an AWS beginner, Cloud Engineer, or aspiring DevOps Engineer, this project will help you understand how serverless applications work in the real world.
๐ฏ What Are We Building?
Our application will:
- Accept a long URL.
- Generate a unique short code.
- Store the URL in Amazon DynamoDB.
- Return a shortened URL.
- Redirect users to the original website when they open the short URL.
Example:
Original URL:
ย
https://www.amazon.com/ย Short URL:
ย
https://your-api-url/abc1234ย ๐๏ธ AWS Architecture
Our project will use these services:
- Amazon API Gateway: Receives HTTP requests.
- AWS Lambda: Runs our Python application without managing servers.
- Amazon DynamoDB: Stores short codes and original URLs.
- Amazon S3 (Optional): Hosts a simple frontend website.
Request Flow:
User โ API Gateway โ Lambda โ DynamoDB
The application returns a short link, and subsequent requests retrieve the original URL and redirect the user.
๐ ๏ธ Step 1: Create a DynamoDB Table
- Open AWS Management Console.
- Search for Amazon DynamoDB.
- Select Tables โ Create table.
- Table name: ย
URLShortenerย
- Partition key: ย
shortCodeย
- Data type: String.
- Click Create table.
Our database will store records like:
shortCode | originalUrl |
|---|---|
abc1234 | ย https://example.comย |
xyz5678 | ย https://amazon.comย |
โก Step 2: Create an AWS Lambda Function
- Open AWS Lambda.
- Click Create function.
- Select Author from scratch.
- Function name: ย
URLShortenerFunctionย
- Runtime: Python 3.12.
- Create the function.
Now open Configuration โ Environment variables and add:
ย
TABLE_NAME = URLShortenerย ๐ Step 3: Configure IAM Permissions
Your Lambda execution role needs permission to access the DynamoDB table.
Attach a policy allowing:
- ย
dynamodb:PutItemย
- ย
dynamodb:GetItemย
Restrict the resource ARN to your URLShortener table instead of granting unnecessary access.
๐ป Step 4: Write Python Code
Open the Lambda Code editor and replace the default code with:
import jsonimport osimport uuidimport boto3๏ปฟ
dynamodb = boto3.resource("dynamodb")table = dynamodb.Table(os.environ["TABLE_NAME"])๏ปฟ
def lambda_handler(event, context):๏ปฟ
method = event.get("requestContext", {}).get( "http", {} ).get("method", "")๏ปฟ
path = event.get("rawPath", "")๏ปฟ
if method == "POST" and path.endswith("/shorten"):๏ปฟ
body = json.loads(event.get("body") or "{}") long_url = body.get("url", "")๏ปฟ
if not long_url.startswith(("https://", "http://")): return { "statusCode": 400, "body": json.dumps({"error": "Invalid URL"}) }๏ปฟ
short_code = uuid.uuid4().hex[:7]๏ปฟ
table.put_item( Item={ "shortCode": short_code, "originalUrl": long_url } )๏ปฟ
return { "statusCode": 201, "headers": {"Content-Type": "application/json"}, "body": json.dumps({ "shortCode": short_code }) }๏ปฟ
if method == "GET":๏ปฟ
short_code = path.rstrip("/").split("/")[-1]๏ปฟ
response = table.get_item( Key={"shortCode": short_code} )๏ปฟ
item = response.get("Item")๏ปฟ
if not item: return { "statusCode": 404, "body": "Short URL not found" }๏ปฟ
return { "statusCode": 302, "headers": { "Location": item["originalUrl"] }, "body": "" }๏ปฟ
return { "statusCode": 404, "body": "Route not found" }Click Deploy.
๐ Step 5: Configure API Gateway
- Open Amazon API Gateway.
- Create an HTTP API.
- Add your Lambda integration.
- Create these routes:
ย
POST /shortenย ย
GET /{shortCode}ย - Connect both routes to your Lambda function.
- Deploy the API to a stage.
Copy your API endpoint URL.
๐งช Step 6: Test Your Project
Now let's test our application!
Send a POST request to:
ย
https://YOUR-API-URL/shortenย Request body:
{ "url": "https://www.amazon.com/"}Expected response:
{ "shortCode": "abc1234"}Now open:
ย
https://YOUR-API-URL/abc1234ย You should be redirected to the original website!
Congratulations! ๐ You've built your own serverless URL shortener on AWS.
๐ฅ Bonus Challenges
Want to take this project to the next level?
Try implementing these additional features:
- Add a custom short URL feature.
- Add URL expiration using DynamoDB TTL.
- Build a frontend using HTML, CSS and JavaScript.
- Host your frontend on Amazon S3.
- Add CloudWatch monitoring and logging.
- Add input validation and rate limiting.
๐ก What Did We Learn?
Through this project, we explored:
โ
AWS Lambda and serverless computing.
โ
API Gateway and HTTP APIs.
โ
DynamoDB database operations.
โ
IAM roles and permissions.
โ
Python and Boto3.
โ
Real-world cloud application architecture.
๐ฌ Let's Discuss!
I have a question for the AWS community:
If you were improving this project, which feature would you implement first?
- User Authentication
- Custom URL Shortening
- Analytics Dashboard
- QR Code Generator
Drop your answer in the comments! ๐
Also, if you build this project, share your experience and challenges. Let's learn and grow together.
If you found this tutorial useful, give it a like and share it with someone learning AWS! โค๏ธ
Happy Building! ๐
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article