,

How to Create a URL Shortener in Simplest Way Using Python

There are many services available in the market to create short URLs from long ones used in various places. Short URLs are easy to remember or type, so they are very popular in the field of digital marketing and promotions.

Ever considered shortening URLs programmatically? Python offers libraries and APIs that can help achieve this without relying on external services. OfCourse in order to track that URL you have to use the API key from Brandly, bitly, tinyurl etc services.

In this article, I’m going to walk you through how to create a URL shortener with Python.

Let’s explore how to build a URL shortner using Python. We’ll write a Python program where we input a long URL and get a short URL as output, all in just a few lines of code.

While it may sound complex, Python’s libraries make this task quite simple. Let’s dive into the steps to create a URL shortener with Python.

First let us generate a code which when run will give a shorten URL in the terminal

import pyshorteners

def make_tiny(url):
s = pyshorteners.Shortener()
return s.tinyurl.short(url)

def main():
url = 'https://codemagnet.in/2024/03/21/automate-let-and-sumifs-functions-with-python-without-using-a-helper-column-in-excel/'
tinyurl = make_tiny(url)
print(tinyurl)

if __name__ == '__main__':
main()

Output:

Explanation of the above code:

  1. import pyshorteners: This line imports a Python library called pyshorteners, which provides functions to shorten URLs.
  2. def make_tiny(url):: This line defines a function called make_tiny that takes a URL as input and returns a shortened version of that URL.
  3. s = pyshorteners.Shortener(): This line creates an instance of the Shortener class from the pyshorteners library, which will be used to shorten URLs.
  4. return s.tinyurl.short(url): This line uses the s object to shorten the given url using the TinyURL service. It returns the shortened URL.
  5. def main():: This line defines a function called main, which is the entry point of the program.
  6. url = 'https://codemagnet.in/2024/03/21/automate-let-and-sumifs-functions-with-python-without-using-a-helper-column-in-excel/': This line defines the URL that we want to shorten.
  7. tinyurl = make_tiny(url): This line calls the make_tiny function with the url as an argument and stores the shortened URL in the tinyurl variable.
  8. print(tinyurl): This line prints the shortened URL to the console.
  9. if __name__ == '__main__':: This line checks if the script is being run directly (as opposed to being imported as a module). If it is being run directly, it calls the main function.

To run this code, you need to have the pyshorteners library installed. You can install it using pip:

pip install pyshorteners

After installing the library, save the code in a file (e.g., shorten_url.py or in my case it is me.py) and run it using Python:

python shorten_url.py

Now let us go ahead and create a application for the same just like bitly or tinyurl applications

We will use Flask, a lightweight web framework for Python, to create a simple URL shortening application.

First, you’ll need to install Flask if you haven’t already. You can do this using pip:

pip install Flask

Step 1: Create a Python script (app.py) with the following code:

from flask import Flask, render_template, request, redirect
import shortuuid
import sqlite3

app = Flask(__name__)

# Database setup
conn = sqlite3.connect('urls.db')
conn.execute('CREATE TABLE IF NOT EXISTS urls (id INTEGER PRIMARY KEY, original_url TEXT, short_url TEXT)')
conn.close()

@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
original_url = request.form['url']
short_url = shortuuid.uuid()[:6] # Generate a short URL
conn = sqlite3.connect('urls.db')
conn.execute('INSERT INTO urls (original_url, short_url) VALUES (?, ?)', (original_url, short_url))
conn.commit()
conn.close()
return redirect('/')
return render_template('index.html')

@app.route('/<short_url>')
def redirect_to_url(short_url):
conn = sqlite3.connect('urls.db')
cursor = conn.execute('SELECT original_url FROM urls WHERE short_url = ?', (short_url,))
original_url = cursor.fetchone()[0]
conn.close()
return redirect(original_url)

if __name__ == '__main__':
app.run(debug=True)

Step 2:

Create a folder named templates in the same directory as app.py. Inside the templates folder, create an HTML file named index.html with the following content:

<!DOCTYPE html>
<html>
<head>
<title>URL Shortener</title>
</head>
<body>
<h1>URL Shortener</h1>
<form method="post">
<input type="text" name="url" placeholder="Enter URL" required>
<button type="submit">Shorten URL</button>
</form>
{% if short_url %}
<p>Shortened URL: <a href="{{ short_url }}">{{ short_url }}</a></p>
{% endif %}
</body>
</html>

Step 3:

Run the Flask application:

python app.py

Explanation of the above code:

  1. from flask import Flask, render_template, request, redirect: Import necessary modules from the Flask framework for creating web applications.
  2. import shortuuid: Import the shortuuid module for generating short unique IDs.
  3. import sqlite3: Import the sqlite3 module for working with SQLite databases.
  4. app = Flask(__name__): Create a Flask application instance.
  5. Database setup:
  6. conn = sqlite3.connect(‘urls.db’)
  7. conn.execute(‘CREATE TABLE IF NOT EXISTS urls (id INTEGER PRIMARY KEY, original_url TEXT, short_url TEXT)’)
  8. conn.close()
  9. Connect to the SQLite database urls.db.
  10. Create a table named urls if it does not exist, with columns id (primary key), original_url, and short_url.
  11. @app.route('/', methods=['GET', 'POST']): Decorator for the home route that accepts both GET and POST requests.
  12. def home():: Define the home route handler function.
    • If the request method is POST, extract the original URL from the form data, generate a short URL, and insert both URLs into the database.
    • Render the index.html template.
  13. @app.route('/<short_url>'): Decorator for dynamic routes that redirect to the original URL.
  14. def redirect_to_url(short_url):: Define the redirect route handler function.
    • Retrieve the original URL associated with the given short URL from the database.
    • Redirect to the original URL.
  15. if __name__ == '__main__':: Check if the script is being run directly.
    • Run the Flask application in debug mode.

You can use such kind of programs while developing any software or a web application. Some more amazing Python projects with code can be found here for your practice. I hope you liked this article on how to create a URL shortener with Python. Feel free to ask your valuable questions in the comments section below.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>