DEV Community

Cover image for Shorten Long URL Using CDK And Serverless
πŸš€ Vu Dao πŸš€
πŸš€ Vu Dao πŸš€

Posted on

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)

- CDK helps to create this project by coding (python language), What's its benefits?

+ Infra structure as code

+ Update lambda function code and just need to execute cdk deploy, all the code and modules will be up-to-date

+ Create and destroy the structure quickly, and we can manage the structure by separate stacks such dynamodb stack, IAM stack, lambda stack and API Gateway stack.

Alt Text

What’s In This Document

πŸš€ Init CDK project

⚑ $ mkdir shorten-url
⚑ $ cd shorten-url
⚑ $ cdk init -l python
Enter fullscreen mode Exit fullscreen mode

πŸš€ Create source code

⚑ $ 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
Enter fullscreen mode Exit fullscreen mode
  • Add python boto3 module for lambda function sources
⚑ $ pip install boto3 -t create_src
⚑ $ pip install boto3 -t redirect_src
Enter fullscreen mode Exit fullscreen mode
  • 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.
Enter fullscreen mode Exit fullscreen mode
  • List stacks
⚑ $ cdk ls
ShortenUrlDDB
ShortenUrlIAMRole
ShortenURLCreateLambda
ShortenURLRedirectLambda
ShortenURLApiGW
Enter fullscreen mode Exit fullscreen mode

πŸš€ Deploy stacks

⚑ $ cdk deploy '*'
Enter fullscreen mode Exit fullscreen mode
  • Full stacks created in cloudformation:
    Alt Text

  • Lambda functions:
    Alt Text

  • Lambda function: create url
    Alt Text

  • Lambda function: redirect url
    Alt Text

  • API Gateway
    Alt Text
    Alt Text

πŸš€ Demo

  • 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\"}"
Enter fullscreen mode Exit fullscreen mode
  • Check dynamodb table
    Alt Text

    • Note that I add expiry_date attribute for TTL = 7 days
  • Click on the short URL

    Alt Text

🌠 Blog · Web · Linkedin · Group · Page · Twitter 🌠

Top comments (0)