Cat skinning

August 2, 2020 Python

Having grown weary of cutting, pasting, copying, pasting repetitively to shorten links, I finally got around to writing a little snippet to do this. This works in Enthought Canopy Python 2.7.6 64-bit (with an annoying warning message about insecure connections) and in Python 3.4.3 Anaconda 2.2.0 (x86_64) with no message. You will need the free API token from bit.ly

# bitlyshort.py
# function to query bitly.com API with bitly provided access credential
# giving a long URL; function returns the bit.ly shortened url
# example
# result = shorten('http://www.example.com')
# result['data']['url']

import requests

#YOUR BITLY PROVIDED CREDENTIAL: see http://dev.bitly.com/get_started.html'
BITLY_GENERIC_ACCESS_TOKEN = 'abcdefghijklmnopqrstuvwxyz01234567890'

def shorten(target):
	query_params = {'access_token': BITLY_GENERIC_ACCESS_TOKEN,
					'longUrl': target} 
	endpoint = 'https://api-ssl.bitly.com/v3/shorten'
	return requests.get(endpoint, params=query_params, verify=True).json()

#print result['data']['url']
# For troubleshooting, full contents of response.json() dictionary object
'''
{'data': {'global_hash': '3hDSUb',
  'hash': '1cdxKEg',
  'long_url': 'http://www.example.com/',
  'new_hash': 0,
  'url': 'http://bit.ly/1cdxKEg'},
 'status_code': 200,
 'status_txt': 'OK'}
'''