[PYTHON] I tried to make a url shortening service serverless with AWS CDK

When I shared a long long link, I wanted to shorten it, so after a lot of research, I found some tutorials. I made a URL shortening service with AWS Cloud Development Kit (CDK) A story about building a URL shortening service that can be used in-house at low cost without a server I created it in the latter tutorial once, but I was disgusted with the fact that CloudFront's custom domain setting did not work and I was sick of popping the console, so I ended up customizing it based on the former tutorial.

Creation flow

cdk setup and tutorial

What is AWS CDK Simply put, it is a tool that allows you to create the resources you need on AWS based on files written in a familiar language. When writing CloudFormation directly, create a configuration file with Json or Yaml, but you can replace it with Python or Typescript. It is necessary to set some IAMs appropriately, but I personally like it because I can write it as if I were saying it. However, the bottleneck is that there are not many samples, and if you are not familiar with AWS terms and resource-related mechanisms, you will not be sluggish. (Personally, I had a hard time because I wasn't used to touching Lambda or Api Gateway.) CDK API list

The introduction of cdk and the creation of the base stack are the same as in the Manma tutorial, so I will omit them. Please refer to the following. I made a URL shortening service with AWS Cloud Development Kit (CDK)

Lock the API Gateway

url_shortener_stack.py


api = aws_apigateway.LambdaRestApi(self, "UrlShortenerApi", handler=handler)

I couldn't find how to lock the API Gateway when using LambdaRestApi, so I implemented it usingRestApi instead.

url_shortener_stack.py


api = aws_apigateway.RestApi(self, "UrlShortenerApi")
shorten_integration = aws_apigateway.LambdaIntegration(shorten_handler)
redirect_integration = aws_apigateway.LambdaIntegration(redirect_handler)

redirect = api.root.add_resource('{proxy}')
redirect_method = redirect.add_method("GET", redirect_integration)#No key

shorten = api.root.add_resource("shorten")
shorten_method = shorten.add_method("GET", shorten_integration, api_key_required=True)#With key

api_key = api.add_api_key('APIKey',api_key_name='BuildAPIKey')#Key creation
plan = api.add_usage_plan('ForAPIKey', api_key=api_key, throttle={
            "rate_limit": 100,
            "burst_limit": 1000
        })#Usage plan creation, key specification
plan.add_api_stage(stage=api.deployment_stage,
                           throttle=[
                               {
                                   "method": shorten_method,
                                   "throttle": {
                                       "rate_limit": 100,
                                       "burst_limit": 1000
                                   }
                               },
                               {
                                   "method": redirect_method,
                                   "throttle": {
                                       "rate_limit": 100,
                                       "burst_limit": 1000
                                   }
                               },
                           ]
                           )#Linking the stage and plan
self.map_company_subdomain('go', api)

In the original sample, it was controlled by Lambda's main function, but it could not be controlled nicely due to lack of power (because the main of lambda fires when the proxy has an arbitrary token, appropriate / token? If you access it in the form of targetUrl =, you can fire the shortening function from the unlocked {proxy} root), make the shortening function and the redirecting function different Lambda functions, and then set each , Linked to APIGateway method and locked abbreviated function.

Receive the shortened result in Json

If you keep the tutorial, it will be returned in text / plain, so change to json

lambda/shorten.py


return {
            'statusCode': 200,
            'headers': {'Content-Type': 'application/json'},
            'body': json.dumps({'shrink_url': url})
        }

Summary

You don't have to go to the console one by one, and cdk diff is convenient for the difference, so I want to use it positively, but I can't write appropriate code unless I have enough knowledge of the underlying AWS resources. This code works for the time being, but I think there are many points that cannot be reached such as API Gateway stage, throttling, keys, integration and control of Lamda functions, so I thought that I should improve it gradually.

Recommended Posts

I tried to make a url shortening service serverless with AWS CDK
[5th] I tried to make a certain authenticator-like tool with python
[2nd] I tried to make a certain authenticator-like tool with python
[3rd] I tried to make a certain authenticator-like tool with python
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
I tried to make a strange quote for Jojo with LSTM
I tried to make a mechanism of exclusive control with Go
I tried to introduce a serverless chatbot linked with Rakuten API to Teams
Python: I tried to make a flat / flat_map just right with a generator
I want to make a game with Python
I tried to make a calculator with Tkinter so I will write it
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
[AWS] [GCP] I tried to make cloud services easy to use with Python
I tried AWS CDK!
I tried to make a ○ ✕ game using TensorFlow
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I tried to make a simple mail sending application with tkinter of Python
[Patent analysis] I tried to make a patent map with Python without spending money
I tried to make a castle search API with Elasticsearch + Sudachi + Go + echo
I tried to make a simple image recognition API with Fast API and Tensorflow
I tried to make a "fucking big literary converter"
I tried to create a table only with Django
I tried to automatically generate a password with Python3
[Introduction to AWS] I tried playing with voice-text conversion ♪
I tried to make something like a chatbot with the Seq2Seq model of TensorFlow
I tried to make a real-time sound source separation mock with Python machine learning
I tried to implement a volume moving average with Quantx
I tried to make various "dummy data" with Python faker
I tried to automatically create a report with Markov chain
I want to make a blog editor with django admin
I want to make a click macro with pyautogui (desire)
I tried to solve a combination optimization problem with Qiskit
I want to make a click macro with pyautogui (outlook)
I tried to get started with Hy ・ Define a class
I tried to sort a random FizzBuzz column with bubble sort.
I tried to make a stopwatch using tkinter in python
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried to divide with a deep learning language model
I tried to make a simple text editor using PyQt
[1 hour challenge] I tried to make a fortune-telling site that is too suitable with Python
I tried uploading / downloading a file to AWS S3 / Azure BlobStorage / GCP CloudStorage with Python
I tried to make a generator that generates a C # container class from CSV with Python
I tried to make a motion detection surveillance camera with OpenCV using a WEB camera with Raspberry Pi
I tried to build a service that sells machine-learned data at explosive speed with Docker
[AWS Hands-on] Let's create a celebrity identification service with a serverless architecture!
I tried to make a system that fetches only deleted tweets
Rubyist tried to make a simple API with Python + bottle + MySQL
I tried to make deep learning scalable with Spark × Keras × Docker
A memorandum when I tried to get it automatically with selenium
I tried to make a regular expression of "amount" using Python
I tried to make a regular expression of "time" using Python
[Python] A memo that I tried to get started with asyncio
I tried to create a list of prime numbers with python
I tried to make a regular expression of "date" using Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I tried to create Bulls and Cows with a shell program
Let's make a web chat using WebSocket with AWS serverless (Python)!