Last active
February 25, 2018 02:14
-
-
Save komasaru/88bd488ddfef478a8adf139fc66c81f6 to your computer and use it in GitHub Desktop.
Python script to shorten a url with bitly API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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