pythonpython-3.xbit.ly

Shortening a long URL with bit.ly v4 (migrate from bit.ly v3) and python 3.7 and bitlyshortener package


I do have some tutorial code that makes use of the bit.ly API v3 for shortening an URL response. I would like to migrate this code to the v4 API but I do not understand how to set up the correct API endpoint. At least I think this is my error and the API documentation is difficult to understand and to adapt for me, as I'm a beginner.

I do have 2 files to work with:

  1. bitlyhelper.py (this needs to be migrated to bit.ly API v4)
  2. views.py

This is the relevant code that relates to the URL shortening.

bitlyhelper.py

import requests
#import json

TOKEN = "my_general_access_token"
ROOT_URL = "https://api-ssl.bitly.com"
SHORTEN = "/v3/shorten?access_token={}&longUrl={}"


class BitlyHelper:

    def shorten_url(self, longurl):
        try:
            url = ROOT_URL + SHORTEN.format(TOKEN, longurl)
            r = requests.get(url)
            jr = r.json()
            return jr['data']['url']
        except Exception as e:
            print (e)

views.py

from .bitlyhelper import BitlyHelper

BH = BitlyHelper()

@usr_account.route("/account/createtable", methods=["POST"])
@login_required
def account_createtable():
    form = CreateTableForm(request.form)
    if form.validate():
        tableid = DB.add_table(form.tablenumber.data, current_user.get_id())
        new_url = BH.shorten_url(config.base_url + "newrequest/" + tableid)
        DB.update_table(tableid, new_url)
        return redirect(url_for('account.account'))
    return render_template("account.html", createtableform=form, tables=DB.get_tables(current_user.get_id()))

The code does work fine when using the v3 API.

I tried a few combinations of the API endpoint, but couldn't get it to work.

for example simply changing the version number does not work.

SHORTEN = "/v4/shorten?access_token={}&longUrl={}"

It would be great if someone could help with setting up the proper API endpoint.

Here is the API documentation: https://dev.bitly.com/v4_documentation.html

This is the relevant part I think:

enter image description here


Solution

  • I got some help and ended up using bitlyshortener from here: https://pypi.org/project/bitlyshortener/

    In this way:

    from bitlyshortener import Shortener
    
    tokens_pool = ['bitly_general_access_token']  # Use your own.
    shortener = Shortener(tokens=tokens_pool, max_cache_size=128)
    
    @usr_account.route("/account/createtable", methods=["POST"])
    def account_createtable():
        form = CreateTableForm(request.form)
        if form.validate():
            tableid = DB.add_table(form.tablenumber.data, current_user.get_id())
            new_urls = [f'{config.base_url}newrequest/{tableid}']
            short_url = shortener.shorten_urls(new_urls)[0]
            DB.update_table(tableid, short_url)
            return redirect(url_for('account.account'))
        return render_template("account.html", createtableform=form, tables=DB.get_tables(current_user.get_id()))
    

    This does work perfectly fine, and bitlyshortener even adds the s to https://my_shortlink automagically.