Question

I have an account with Bitly which personalizes my URL shortening. How can I use the API to sign in and shorten a list of URLs?

Was it helpful?

Solution

Here is my solution in python using python requests library

    import base64 
    import requests
    import json 

    credentials = 'USERNAME:PASSWORD'

    urls = ['www.google.com', 'www.google.co.uk', 'www.google.fr']

    def getShortURLs(urls):
        token = auth()
        return shortenURLs(token, urls)

    def auth():
        base_auth = "https://api-ssl.bitly.com/oauth/access_token"
        headers = {'Authorization': 'Basic ' + base64.b64encode(credentials)}
        resp = requests.post(base_auth, headers=headers)
        return resp.content

    def shortenURLs(token, long_urls):
        base = 'https://api-ssl.bitly.com/v3/shorten'
        short_urls = []
        for long_url in long_urls:
            if long_url:
                params = {'access_token':token, 'longUrl' : 'https://' + long_url}
                response = requests.get(base, params=params)
                r = json.loads(response.content)
                short_urls.append(r['data']['url'])
        return short_urls
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top