4

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

Zoe
  • 27,060
  • 21
  • 118
  • 148
mks
  • 422
  • 5
  • 15

3 Answers3

6
import requests

header = {
    "Authorization": "Bearer <TOKEN HERE>",
    "Content-Type": "application/json"
}
params = {
    "long_url": form.url.data
}
response = requests.post("https://api-ssl.bitly.com/v4/shorten", json=params, headers=header)
data = response.json()
if 'link' in data.keys(): short_link = data['link']
else: short_link = None

First you want to create the request header with your bearer token. Make sure to set the content type too. After setting your header you have to provide the url you would like to shorten for example.

The data variable contains your 201 request.

YetAnotherDuck
  • 294
  • 4
  • 13
4

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.

Asclepius
  • 57,944
  • 17
  • 167
  • 143
mks
  • 422
  • 5
  • 15
3

It makes sense that your v3 code fails against v4, based on this:

Authentication

How you authenticate to the Bitly API has changed with V4. Previously your authentication token would be provided as the access_token query parameter on each request. V4 instead requires that the token be provided as part of the Authorization header on each request.

You will want to move your token out of the args and into the header.

Using https://github.com/bitly/bitly-api-python might possibly be an option, except that it is some years since it was last updated.

J_H
  • 17,926
  • 4
  • 24
  • 44