Pythons Project for beginners - Post 27: Simple URL Shortener
- Anubhav Somani
- Sep 6
- 2 min read

Let's build a Simple URL Shortener. This is a very practical, real-world project that builds on the concept of using APIs. It shows how Python can connect to web services to perform useful tasks.
First, here is the explanation of how the project is built.
How the "Simple URL Shortener" is Made
The Core Idea: The goal is to create a command-line tool that takes a long web URL from a user and uses an online service to generate a much shorter, more manageable URL that still directs to the same page.
Required Modules: This project requires the requests library, which is the standard for making HTTP requests in Python. If you don't have it installed, you'll need to run pip install requests in your terminal.
Choosing an API: We need a URL shortening service that provides a simple, free API. For this project, we'll use tinyurl.com because it offers a free, keyless API that is incredibly easy for beginners to use. You simply make a request to a specific URL, and it returns the shortened link as plain text.
The API Endpoint: The URL for the TinyURL API is http://tinyurl.com/api-create.php. To use it, you just add ?url= followed by the long URL you want to shorten. For example: http://tinyurl.com/api-create.php?url=https://www.google.com.
The Core Logic:
Get User Input: The program starts by asking the user to enter the long URL they wish to shorten.
Construct the Request URL: We take the user's input and append it to the base API endpoint to create the full request URL.
Make the API Request: We use requests.get() to send a request to the constructed URL. It's crucial to wrap this call in a try...except block to handle potential network issues, like being offline.
Check the Response: After the request is made, we check the response.status_code. A code of 200means the request was successful. If we get a different code, it means something went wrong, and we should inform the user.
Get the Short URL: Unlike many APIs that return complex JSON, this API is very simple. If the request is successful, the body of the response (response.text) is the shortened URL itself.
Display the Result: We then print this short URL to the user with a clear success message.



Comments