All other requests are served from S3 from a specific folder named “u” that stores all redirection objects.All requests for the “/prod/” prefix are sent to API Gateway.All requests for the “/admin/” prefix serve static HTML files from S3.To avoid CORS configuration and have a simple friendly domain name, wrap all pieces behind a single Amazon CloudFront distribution as shown in the diagram below. Using Amazon CloudFront to wrap everything together
Tinyurl api code#
The code in Lambda simply stores an empty object in S3 with a random 7-character name, and assigns the metadata for the HTTP redirect. When you choose Shorten, it triggers a POST request to API Gateway, which securely invokes a Lambda function (~70 lines of code) after validating all parameters. In order to create redirection objects, you need a simple admin page: a static HTML page hosted in S3 and built with jquery. To avoid proliferation of these redirect objects, you can enable a lifecycle policy to automatically delete objects, for example, after 7 days. For more information, see Configuring a Web Page Redirect.
When the end user hits the short URL, S3 automatically responds with a HTTP redirect to the target (long) URL, without you needing any code. Then you create an empty object for each short URL (a random 5-character ID) and attach the “website redirect” metadata with the target (long) URL. It’s a little known feature: S3 can act as a redirection engine.įirst, you need to activate “website hosting” on your S3 bucket. This next graphic shows a generated short URL ready to copy and paste. The following graphic shows the admin page. Because you don’t need to manage your own servers anymore, it’s easy to build applications that are natively scalable, secure, resilient, and very cost effective.
Tinyurl api how to#
In this post, you’ll see how to build your own private URL shortener using a serverless architecture, which leaves you with full control over your application while leveraging managed AWS services like AWS Lambda, AWS API Gateway, and S3. This is when I realized it was super easy to build a private one. As this content is often confidential, I tend to avoid using public URL shortener services. It’s more convenient and user-friendly to generate a shortened URL. However, S3 pre-signed URLs are generally over 250 characters and may be split in several lines by email clients. To avoid sending heavy attachments in email, I first upload the content on Amazon S3, then send a pre-signed URL to allow the customer to securely download the content. As a solutions architect, I often need to send large files to customers, such as architecture diagrams and service presentations.