-1

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?

TRiG
  • 10,148
  • 7
  • 57
  • 107
david_adler
  • 9,690
  • 6
  • 57
  • 97
  • 1
    [Authenticate yourself with OAuth2](http://dev.bitly.com/authentication.html) then call [/v3/shorten](http://dev.bitly.com/links.html#v3_shorten) for each one? Which specific part do you need help with? – Rup Sep 17 '13 at 08:45
  • -1 read the docs. http://dev.bitly.com/api.html – user247702 Sep 17 '13 at 08:46
  • Fair enough @Stijn,the answer is in the docs. Buts sometimes SO is a quicker option... Now the next time somebody wants this specific answer they don't have to go through the docs. I hope my answer saves somebody 20 mins of walking through docs for 30 secs of taking my code. – david_adler Sep 21 '13 at 12:51
  • This is looking for a tutorial, rather than help with code. – TRiG Jan 11 '14 at 01:15

1 Answers1

1

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
david_adler
  • 9,690
  • 6
  • 57
  • 97