Play this article
- There are many web apps provide the service of shortening your long url (free or charge). 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.
Whatβs In This Document
π Init CDK project
β‘ $ mkdir shorten-url
β‘ $ cd shorten-url
β‘ $ cdk init -l python
π Create source code
Source: shorten-url
β‘ $ 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
π Deploy stacks
β‘ $ cdk deploy '*'
Full stacks created in cloudformation:
Lambda functions:
Lambda function: create url
Lambda function: redirect url
API Gateway
π 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\"}"
Check dynamodb table
- Note that I add
expiry_date
attribute for TTL = 7 days
- Note that I add
Click on the short URL
Project vercel: cdk-serverless-shorten-url.vercel.app Github Code π©βπ» : github.com/vumdao/shorten-url