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:
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With