Regarding the new Bit.ly API in Python

98 Views Asked by At

Seemingly the bit.ly API has been updated a lot in recent years. Here is the website of the latest API documentation https://dev.bitly.com/api-reference

I am trying to do the simplest operation, i.e., shortening a long URL. I have generated a token following the instructions, and below is the code I tried following the example (https://dev.bitly.com/api-reference/#createBitlink) where I used my token instead of the string "my token" here:

import requests

headers = {
    "Authorization": "Bearer {my token}",
    "Content-Type": "application/json",
}

data = '{ "long_url": "https://dev.bitly.com", "domain": "bit.ly"}'

response = requests.post(
    "https://api-ssl.bitly.com/v4/shorten", headers=headers, data=data
)

But the response is 403. Is there anyone who is familiar with the bit.ly API? Any help will be appreciated!

A related question: getting bit.ly to return shortened URL

1

There are 1 best solutions below

1
On

Sorry for the confusion... It is seemingly okay now. Below is an example extended from https://dev.bitly.com/api-reference/#createBitlink

import requests
import sys

input_url = sys.argv[1]
longurl = "https://"  + input_url if not input_url.startswith("https://") else input_url
print(longurl)

token = "find your token at https://app.bitly.com/settings/api/"

headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json",
}

data = '{ "long_url": "' + longurl + '", "domain": "bit.ly"}'
# print(data)


response = requests.post(
    "https://api-ssl.bitly.com/v4/shorten", headers=headers, data=data
)

try:
    print(response.json()["link"])
except:
    print(response)    
    print(response.json())
python bitly.py https://stackoverflow.com/questions/75279574
https://stackoverflow.com/questions/75279574
https://bit(dot)ly/3DqI7Ea