AWS Serverless URL Shortener - Part 1

Posted • 2 minute read

One of our business’s had a need for a url shortener with both a front end & programmatic access for use in campaigns. We could have utilised a paid / hosted service, but it seemed like a great opportunity to create a serverless application in AWS by leveraging lambda.

Requirements

The requirements for this url shortener were:

  • Extremely reliable, cost effective, low maintenance
  • Both Programmatic & Gui access
  • Ability to use a custom domain name
  • Utilise https
  • Create multiple short url’s for a single long url (for multi avenue campaigns)
  • Keep a count of number of clicks for a short url

Overview

AWS Serverless URL Shortener - Part 1 https://d33wubrfki0l68.cloudfront.net/e92f5e93e9b7043cf511caaa31242ce8f5744e8b/d5ff3/images/uploads/overview.png

The AWS components are fairly simple:

Certificate Manager can generate a free SSL Certificate to use with API Gateway to enable https on the service

S3 will be used to host a static site to form the front end which will make calls to the API Gateway

API Gateway will expose a POST & GET method for submitting and returning urls

Lambda does all the heavy lifting, generating short urls, then submitting or retrieving them from DynamoDB

DynamoDB will be the store for all of the url pairs (and sticks with the serverless theme)

DynamoDB

Start by creating a new DynamoDB with the following settings:

Name: redir_urls
Primary Key: token
Read Capacity: 1
Write Capacity: 1

AWS Serverless URL Shortener - Part 1 https://d33wubrfki0l68.cloudfront.net/17034516d2b86ed3675dca04f9974db67d95ee57/a1cf8/images/uploads/dynamodb-1.png


API Gateway

Create a new API with the linked Swagger file
You will need to enable CORS:

AWS Serverless URL Shortener - Part 1 https://d33wubrfki0l68.cloudfront.net/5ced6995eed627cc791fe0929e0511eb6af22e6d/0faf2/images/uploads/apigateway-1.png

Deploy the API & Associate an API Key for the POST function:

AWS Serverless URL Shortener - Part 1 https://d33wubrfki0l68.cloudfront.net/35342be5b21994de9431c120c767e6e8070bcd8f/af7a3/images/uploads/apigateway-2.png


Lambda

Use the provided Apex framework to deploy the lambda functions.

NOTE: References to Amazon account id have been replaced with {{YOUR AWS ACCOUNT ID}}. You will need to change these to your numeric AWS account id.

Once Apex is installed, deploy via terminal:

1
2
cd lambda
apex deploy

And to test locally:

1
2
cd lambda
echo '{ "token":"xxxxxxx" }' | apex invoke lookup_token