Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active February 25, 2018 02:14
Show Gist options
  • Save komasaru/88bd488ddfef478a8adf139fc66c81f6 to your computer and use it in GitHub Desktop.
Save komasaru/88bd488ddfef478a8adf139fc66c81f6 to your computer and use it in GitHub Desktop.
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