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:
import pyshorteners: This line imports a Python library calledpyshorteners, which provides functions to shorten URLs.def make_tiny(url):: This line defines a function calledmake_tinythat takes a URL as input and returns a shortened version of that URL.s = pyshorteners.Shortener(): This line creates an instance of theShortenerclass from thepyshortenerslibrary, which will be used to shorten URLs.return s.tinyurl.short(url): This line uses thesobject to shorten the givenurlusing the TinyURL service. It returns the shortened URL.def main():: This line defines a function calledmain, which is the entry point of the program.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.tinyurl = make_tiny(url): This line calls themake_tinyfunction with theurlas an argument and stores the shortened URL in thetinyurlvariable.print(tinyurl): This line prints the shortened URL to the console.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 themainfunction.
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:
from flask import Flask, render_template, request, redirect: Import necessary modules from the Flask framework for creating web applications.import shortuuid: Import theshortuuidmodule for generating short unique IDs.import sqlite3: Import thesqlite3module for working with SQLite databases.app = Flask(__name__): Create a Flask application instance.- 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()
- Connect to the SQLite database
urls.db. - Create a table named
urlsif it does not exist, with columnsid(primary key),original_url, andshort_url. @app.route('/', methods=['GET', 'POST']): Decorator for the home route that accepts both GET and POST requests.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.htmltemplate.
@app.route('/<short_url>'): Decorator for dynamic routes that redirect to the original URL.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.
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.





Leave a Reply