Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 666
mks Avatar asked May 04 '19 18:05

mks


1 Answers

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.

like image 146
0x78f1935 Avatar answered Nov 15 '22 04:11

0x78f1935