Build a Simple URL Shortener With Python

[ad_1]

A uniform resource locator — or, more commonly, URL — is the address of content on the internet. URLs often feature the address of a web page followed by a long string of seemingly random characters. These can be unsightly and unmemorable. Fortunately, there are tools called URL shorteners that can minimize them.

Shortening a URL has several benefits, including making the address easier to share and less likely to be typed inaccurately by users. Even one missing character in a URL can make it completely useless, directing users to the wrong page or to a resource that doesn’t even exist.

Take the example of https://example.com/blog-url-shorteners/48bfefiahl9adik shortened to https://example.com/url-shorteners. It’s not hard to see which a user would be more prone to share, or which might be more likely to lead to mistakes while typing.

A URL shortener’s benefits go beyond tidying up long URLs. They can also help with the following:

  • Improving ranking in search engines: Content creators, businesses, and start-ups all have content on their websites, blogs, or social media. Search engines prefer links with specific keywords so they can be ranked accordingly and generate good results. A short URL generated from a known platform can help rank your URL higher.
  • Tracking traffic on your links: Paid URL shortener services like Bitly help you track the users clicking your links so you can analyze your incoming traffic and customize your content accordingly.

Two Approaches to a URL Shortener: A Python Library and an API

Following the instructions in this tutorial, you’ll build a URL shortener web app with Python using two different methods:

The pyshorteners module is used by developers to generate short URLs, while the Bitly API module generates short URLs and provides more robust functions like clicks per URL, locations of clicked URLs, customization of URLs, and more.

To complete the tutorial, you’ll need a basic knowledge of Python, and Python must be installed on your system.

Setting Up the Project Environment

Before creating your URL shortener web app, you need to set up the environment for the project, including the installation of Flask, a lightweight framework that makes developing Python web apps easier.

Begin with these steps:

  • Create a project folder, perhaps with a name like url-shortener.
  • Create an empty file named main.py within that folder.
  • Create a virtual environment for this project so that any installation of Python libraries remains independent of your system. Use the command python -m venv myenv in your terminal to create that environment. (In this case, the environment files will be placed in the directory myenv.)
  • Activate the virtual environment using the corresponding command for your operating system (and where <myenv> is the name of the directory you created in the previous step).
    • Windows: <myenv>\Scripts\activate.bat
    • Linux/macOS: source <myenv>/bin/activate
  • Install Flask using the command pip install flask.
  • Create a folder named templates in the project folder. (Flask will retrieve the HTML templates from this directory.)

Your work in the terminal so far will look something like this:

Commands entered in the terminal to create the Python project environment.
The Python project so far in a macOS terminal.

Using the pyshorteners Library to Build a URL Shortener Web App

With your project environment set up, you’ll now create your first URL shortener using the pyshorteners library.

Install the pyshorteners library with the following command:

pip install pyshorteners

Creating a Basic User Interface for the Web Application

Next, you’ll create a basic form in HTML with labels and input fields, where you enter a long URL and generate a shorter one.

Create a form.html file in the templates folder, then enter the following code in that file and save it:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>URL Shortener</title>
</head>
<body>
  <h1>URL Shortener</h1>
  <form method="post" action="/">
    <label for="url">Enter an https:// URL:</label>
    <input type="url"
      name="url"
      id="url"
      placeholder="https://www.xyz.com"
      pattern="https://.*" size="50"
        value="{{old_url}}"
      required  
    >
    <button type="submit" value="submit">Submit</button>
    <br>
    <label>Generated URL: </label>
    <input name="generated_url" value="{{new_url}}" style="margin-top: 10px; margin-left:35px" size="50"></input>
  </form>
</body>
</html>

The above code creates a form with two labels, two input fields, and one button.

The first input field called url, is for writing the long URL, and the other field is for generating the short URL.

The url input field has the following attributes:

  • name: To identify the element (e.g., URL)
  • placeholder: To show a URL example
  • pattern: To specify the pattern of a URL which is https://.*
  • required: To give a URL input before submitting
  • value: To view the old URL

The second input field has a value attribute set to new_url. The new_url is a short URL generated by the pyshorteners library from the main.py file (shown in the next section).

The entry form is depicted in the following screenshot:

Screenshot of a web form for shortening URLs.
A web form for the URL shortener.

URL Shortening Code Using pyshorteners

Now that you’ve created the form, you can add some functionality to it using Python and pyshorteners.

You’ll add code to process the long URL into a short one and run the web application. Navigate to the main.py file you created earlier, enter the following code, and save it:

from flask import Flask, render_template, request
import pyshorteners
app = Flask(__name__)
 
@app.route("/", methods=['POST', 'GET'])
def home():
  if request.method=="POST":
    url_received = request.form["url"]
    short_url = pyshorteners.Shortener().tinyurl.short(url_received)
    return render_template("form.html", new_url=short_url, old_url=url_received)
  else:
    return render_template('form.html')
 
if __name__ == "__main__":
 app.run() 

The code above imports the pyshorteners library and the following modules from the Flask framework, all of which you’ll need for shortening URLs:

  • Flask: The Flask framework itself, which was previously introduced.
  • render_template: A template rendering package used to generate the output of HTML files from the folder templates.
  • request: An object from the Flask framework that contains all the data that a user sends from the frontend to the backend as a part of an HTTP request.

Next, it creates a function called home() that takes a URL submitted in the form and outputs a short URL. The app.route() decorator is used to bind the function to the specific URL route for running the app, and the POST/GET methods handle the requests.

In the home() function, there’s an if-else conditional statement.

For the if statement, if request.method=="POST", a variable called url_received is set to request.form["url"], which is the URL submitted in the form. Here, url is the name of the input field defined in the HTML form created earlier.

Then, a variable called short_url is set to pyshorteners.Shortener().tinyurl.short(url_received).
Here, two methods are used from the pyshorteners library: .Shortener() and .short(). The .Shortener() function creates a pyshorteners class instance and the .short() function takes in the URL as an argument and shortens it.

The short() function, tinyurl.short(), is one of the pyshorteners library’s many APIs. osdb.short() is another API that can also be used for the same purpose.

The render_template() function is used to render the HTML file template form.html and send URLs back to the form through arguments. The new_url argument is set to and old_url is set to url_received. The if statement’s scope ends here.

For the else statement, if the request method is other than POST, only the form.html HTML template will be rendered.

Demonstration of the URL Shortener Web App Built with the pyshorteners Library

To demonstrate the pyshorteners URL shortener application, navigate to the default route for the application, http://127.0.0.1:5000/, after running the application.

Paste a link of your choice into the first field of the web form:

Screenshot of URL to be shortened pasted into web form.
Testing the URL shortener using the pyshorteners library.

Click the Submit button to output a short URL with tinyurl as the domain in the Generated URL field:

Screenshot showing shortend URL returned in web form.
Result of URL shortening using the pyshorteners library.

Using the Bitly API Module to Build a URL Shortener Web App

In this section, you’ll develop a URL-shortening application using the Bitly API. As mentioned, the Bitly API module is another method for shortening URLs and also provides detailed analytics on clicks, location, and device type used (such as desktop or mobile).

Install the Bitly API using the following command:

pip install bitly-api-py3

You need an access token to use the Bitly API, which you can get by signing up with Bitly.

After completing the signup process, log in to Bitly to view your dashboard:

Screenshot of the Bitly dashboard.

Click Settings on the left sidebar, then click the API section found under Developer settings.

Generate an access token by entering your password in the field above the Generate token button, as shown in the image below, and keep the token to use in the code for your app:

Screenshot of access token generation for the Bitly API/
Generating an access token for the Bitly API.

URL Shortening Code Using the Bitly API

Now that you have the token from Bitly, you can code the web app to shorten the URL using the Bitly API.

You’ll use the same form you created for the pyshorteners section but with some changes to the main.py file:

from flask import Flask, render_template, request
import bitly_api
app = Flask(__name__)
 
bitly_access_token = "37b1xxxxxxxxxxxxxxxxxxxxxxxxxx"
 
@app.route("/", methods=['POST', 'GET'])
def home():
  if request.method=="POST":
    url_received = request.form["url"]
    bitly = bitly_api.Connection(access_token=bitly_access_token)
    short_url = bitly.shorten(url_received)
    return render_template("form.html", new_url=short_url.get('url'), old_url=url_received)
  else:
    return render_template('form.html')
 
if __name__ == "__main__":
 app.run() 

As you can see from the code above, bitly_api is imported using import bitly_api. The access token is then saved in a variable called bity_access_token, as in bitly_access_token = "37b1xxxxxxxxxxxxxxxxxxxxxxxx".

The home() function shortens the URL and contains an if-else conditional statement.

For the if statement, if the method or request is POST, then the URL submitted in the form is set to the url_received variable.

The bitly_api.Connection(access_token=bitly_access_token) function connects to the Bitly API and passes it the access token you saved earlier as an argument.

To shorten the URL, the bitly.shorten() function is used by passing the url_received variable as an argument and saving it in a variable called short_url.

Finally, the created form is rendered, and URLs are sent back to be shown in the form using the render_template() function. The if statement completes here.

For the else statement, the form is rendered using the render_template() function.

Demonstration of the URL Shortener Web App Built with the Bitly API

To demonstrate the Bitly API URL shortener application, navigate to the default route for the application, http://127.0.0.1:5000/, after running the application.

Paste a link of your choice into the first field of the web form:

Screenshot of web form for Bitly URL shortener API.
Testing the URL shortener using the Bitly API.

Click Submit to generate a short URL with bit.ly as the domain in the second field of the web application:

Screenshot of shortened URL returned by the Bitly API.
Result of URL shortening using the Bitly API.

Using the Bitly API to shorten URLs in your Python application is a simple as that.

Summary

URL shorteners give you short URLs that are easy to share, look cleaner, and take up less space. In this article, you learned about URL shorteners and their benefits, as well as how to create a URL shortener web application with Python using pyshorteners and the Bitly API. The pyshorteners library provides short URLs, while the Bitly API provides detailed analytics as well as short URLs.

Since you’ve already made an awesome app, why not take it to the next level and host it on Kinsta’s Wed Application Hosting service? To help you get a Python app like this up and running on our platform, explore our Flask quick start tutorial.

Adarsh Chimnani

Adarsh is a web developer (MERN stack), passionate about game-level designing (Unity3D), and an anime enthusiast. He enjoys absorbing knowledge just out of curiosity, implementing what he has learned in the real world, and sharing that knowledge with others.

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
Jassweb, Rai Chak, Punjab, India. 143518