#! /usr/local/bin/python3.6"""URL shorten with bitly API v3"""importjsonimportrequestsimportsysimporttracebackimporturllibclassUrlShortenBitly:URL="https://api-ssl.bitly.com/v3/shorten"TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"defshorten(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"])exceptExceptionase:raiseif__name__=='__main__':url_long="https://www.mk-mode.com/octopress/2018/02/25/python-napier-computation/"try:obj=UrlShortenBitly()obj.shorten(url_long)exceptExceptionase:traceback.print_exc()
$ ./bitly_shorten.py
STATUS CODE: 200 OK
LONG URL: https://www.mk-mode.com/octopress/2018/02/25/python-napier-computation/
SHORT URL: http://bit.ly/2BNW2VS