Welcome back to PyMakers, your hub for Python projects that simplify and enhance your digital experiences. In this project, we’re diving into the world of URLs and links by building a “URL Shortener” using Python. A URL Shortener is a handy tool for transforming long and complex web addresses into concise and shareable links.

Why a URL Shortener

Long URLs can be cumbersome and challenging to share, especially in printed materials or on social media. By creating a URL Shortener in Python, you’ll not only learn about web requests and string manipulation but also have a practical solution for making your links more user-friendly. It’s a project that combines convenience and efficiency.

The Python Code

Let’s jump straight into the Python code for our URL Shortener:

import requests

def shorten_url(url):
    response = requests.post("https://tinyurl.com/api-create.php", data={"url": url})
    if response.status_code == 200:
        return response.text
    else:
        return "Failed to shorten the URL."

print("Welcome to the URL Shortener!")

while True:
    original_url = input("Enter the URL you want to shorten: ")
    shortened_url = shorten_url(original_url)
    print("Shortened URL:", shortened_url)

    another = input("Shorten another URL? (yes/no): ").lower()
    if another != "yes":
        print("Thank you for using the URL Shortener!")
        break

How it Works

  1. We import the requests module for making HTTP requests to the TinyURL API.
  2. We define a shorten_url() function that takes a long URL as input and sends a request to the TinyURL API to shorten it.
  3. Inside the program loop, the user enters the original URL they want to shorten.
  4. We call the shorten_url() function to obtain the shortened URL from the TinyURL API.
  5. The shortened URL is displayed to the user.
  6. The user has the option to shorten another URL or exit the program.

Conclusion

Congratulations! You’ve just created a Python URL Shortener. This project simplifies the process of transforming long URLs into short, shareable links.

Whether you’re sharing links in printed materials or making your online posts more concise, the URL Shortener is a valuable addition to your digital toolkit. Stay tuned for more Python projects that simplify and enhance your digital experiences. Happy coding! 🐍✨