A mini project that shortens urls with Shorte.st using python. Shorte.st only provides the “curl” command version of the API. In this post, the command is translated in the form of python requests for easy integration with rest of python scripts and enable multiple urls shortening.
Please note that I have an account with Shorte.st.
- Objectives:
-
- Create python function to shorten url using Shorte.st
-
- Required Tools:
-
- Requests — for handling HTML protocol. Use pip install requests.
- Shorte.st account — Shorte.st account to shorten url.
-
- Steps:
-
- Retrieve the API token from Shorte.st by going to Link Tools –> Developer API and copy the API token.
- Use request.put with the following parameters:
- headers containing the API token and user-agent
- data which contains the target url to shorten.
- Get the response.text which contain the shortened url
- Complete! Include shortened url in target sites/twitter/social media etc.
-
Curl commands as provided by Shorte.st
curl -H "public-api-token: your_api_token" -X PUT -d "urlToShorten=target_url_to_shortened.com" https://api.shorte.st/v1/data/url
Python function to insert to part of your code or as standalone
import os, sys, re import requests USER_AGENT = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36" def shorten_url(target_url, api_token): """ Function to shorten url (With your shorte.st) account. Args: target_url (str): url to shorten api_token (str): api token str Returns: shortened_url (str) """ headers = {'user_agent':USER_AGENT, 'public-api-token':api_token} data = dict(urlToShorten=target_url) url = 'https://api.shorte.st/v1/data/url' r= requests.put(url, data, headers= headers) shortened_url = re.search('"shortenedUrl":"(.*)"',r.text).group(1) shortened_url = shortened_url.replace('\\','') return shortened_url if __name__ == "__main__": api_token = 'your_api_token' urllist = [ 'https://simply-python.com/2018/07/20/fast-download-images-from-google-image-search-with-python-requests-grequests', 'https://simply-python.com/2018/04/22/building-a-twitter-bot-with-python' ] for target_url in urllist: shortened_url = shorten_url(target_url, api_token) print 'shortened_url: {}'.format(shortened_url)
Results
shortened_url: http://destyy.com/wKqD2s shortened_url: http://destyy.com/wKqD17
Further notes
- If you have some fantastic links to share and hope to monetize your links, you can click on below banner to explore more.
- The above script is not meant for spamming with huge amount of urls. Shorte.st will monitor on the quality of the urls be shortened.
- An ads-free shortener will be with bit.ly. Please see post on using the bit.ly shortener with python if prefer an alternative.