Have you ever wondered how URL shortening services work? They take a very long URL and give a shortened, crisp, and memorable URL back to the user. At first sight, it looks like magic, but it is a simple math trick.
In a single statement, URL shortening services are built upon two things:
- A string mapping algorithm to map long strings to short strings ( Base 62)
- A simple web server that redirects a short URL to the original URL
There are a few obvious advantages of URL shortening:
- Users can remember the URL; easy to maintain
- Users can use the links where there are restrictions on text length; for example, Twitter
- Predictable shortened URL length
Take a look at the following diagram:
Under the hood, these things happen silently in a URL shortening service:
- Take the original URL.
- Apply Base62 encoding on it. It generates a shortened URL.
- Store that URL in the database. Map it to the original URl ([shortened_url: orignial_url]).
- Whenever a request comes to the shortened URL, just do an HTTP redirect to the original URL.
We will implement the complete logic in upcoming chapters when we integrate databases to our API server, but before that, though, we should specify the API design documentation. Let us do that. Take a look at the following table:
URL | REST Verb | Action | Success | Failure |
/api/v1/new | POST | Create a shortened URL | 200 | 500, 404 |
/api/v1/:url | GET | Redirect to original URL | 301 | 404 |
As an exercise, the reader is allowed to implement this from the fundamentals we have built thus far. You can use a dummy JSON file instead of a database like we did in the first chapter. We will implement this in upcoming chapters, anyway.