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:
- bitlyhelper.py (this needs to be migrated to bit.ly API v4)
- 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: