Skip to content

Instantly share code, notes, and snippets.

@komasaru komasaru/bitly_shorten.py
Last active Feb 25, 2018

Embed
What would you like to do?
Python script to shorten a url with bitly API.
#! /usr/local/bin/python3.6
"""
URL shorten with bitly API v3
"""
import json
import requests
import sys
import traceback
import urllib
class UrlShortenBitly:
URL = "https://api-ssl.bitly.com/v3/shorten"
TOKEN = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
def shorten(self, url_long):
try:
url = self.URL + "?" \
+ urllib.parse.urlencode({
"access_token": self.TOKEN,
"longUrl": url_long
})
res = requests.get(url)
j = json.loads(res.text)
print("STATUS CODE:", j["status_code"], j["status_txt"])
print(" LONG URL:", j["data"]["long_url"])
print(" SHORT URL:", j["data"]["url"])
except Exception as e:
raise
if __name__ == '__main__':
url_long = "https://www.mk-mode.com/octopress/2018/02/25/python-napier-computation/"
try:
obj = UrlShortenBitly()
obj.shorten(url_long)
except Exception as e:
traceback.print_exc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.