Alt Text
Alt Text

Shorten Long URL Using CDK And Serverless

- There are many web apps provide the service of shortening your long url (free or charged). This ariticle introduces the way of using serverless with Cloud development toolkit (CDK)

Alt Text
Alt Text
Alt Text
⚡ $ mkdir shorten-url
⚡ $ cd shorten-url
⚡ $ cdk init -l python
⚡ $ tree
.
├── app.py
├── create_src
│ └── createShortUrl.py
├── README.md
├── redirect_src
│ └── redirectUrl.py
├── requirements.txt
├── setup.py
├── shorten_url
│ ├── __init__.py
│ └── shorten_url_stack.py
  • Add python boto3 module for lambda function sources
⚡ $ pip install boto3 -t create_src
⚡ $ pip install boto3 -t redirect_src
  • Cdk synth to check cdk valid
⚡ $ cdk synth
Successfully synthesized to ~/shorten-url/cdk.out
Supply a stack id (ShortenUrlDDB, ShortenUrlIAMRole, ShortenURLCreateLambda, ShortenURLRedirectLambda, ShortenURLApiGW) to display its template.
  • List stacks
⚡ $ cdk ls
ShortenUrlDDB
ShortenUrlIAMRole
ShortenURLCreateLambda
ShortenURLRedirectLambda
ShortenURLApiGW
⚡ $ cdk deploy '*'
  • Full stacks created in cloudformation:
Alt Text
Alt Text
Alt Text
  • Lambda functions:
Alt Text
Alt Text
Alt Text
  • Lambda function: create url
Alt Text
Alt Text
Alt Text
  • Lambda function: redirect url
Alt Text
Alt Text
Alt Text
  • API Gateway
Alt Text
Alt Text
Alt Text
Alt Text
Alt Text
Alt Text
  • POST a long url (here is not actually long)
⚡ $ curl -L -X POST 'https://s.cloudopz.co/shortenUrl' -H 'Content-Type: application/json' --data-raw '{"url": "https://hashnode.com/@vumdao"}'
"{\"short_url\": \"https://s.cloudopz.co/dVkiBRM\"}"
  • Check dynamodb table
Alt Text
Alt Text
Alt Text
  • Note that I add expiry_date attribute for TTL = 7 days
  • Click on the short URL
Alt Text
Alt Text
Alt Text

Awesome Devops || CloudOpz