Python | How to shorten long URLs using Bitly API

Bitly is used to shorten, brand, share, or retrieve data from links programmatically.

In this article, we’ll see how to shorten URLs using Bitly API. Below is a working example to shorten a URL using Bitly API.

Step #1: Install Bitly API using git
git clone https://github.com/bitly/bitly-api-python.git



Go inside the folder using:
cd bitly-api-python

Note: In case installation with pip command is not working:

filter_none

edit
close

play_arrow

link
brightness_4
code

File "/usr/local/lib/python3.5/dist-packages/bitly_api/__init__.py", line 1, in 
from bitly_api import Connection, BitlyError, Error
  
ImportError: cannot import name 'Connection'

chevron_right


Uninstall bitly-api in case already installed using pip:

pip uninstall bitly_api

 

Step #2: Install in Python’s folder for modules:

python setup.py install

Note: Delete the source code using (since we don’t need it for now) :

cd../
rmdir bitly-api-python-master

 
Step #3: To get “Bitly username and API Key” login to account on bit.ly and then go here and get it. In case of further assistance, one can go here.

 
Step #4: Now create a file shorturl.py and write this code:

filter_none

edit
close

play_arrow

link
brightness_4
code

import bitly_api
  
API_USER = "your_username"
API_KEY = "your_API_Key"
  
b = bitly_api.Connection(API_USER, API_KEY)
  
# Replace this with your Long URL Here
longurl = www.google.com    
response = b.shorten(uri = longurl)
  
# Now let us print the Bitly URL
print(response)

chevron_right


Step #5: Run the file ‘shorturl.py’.

 
Reference: https://dev.bitly.com/v4_documentation.html



My Personal Notes arrow_drop_up

A core developer who has worked on various projects in HTML, CSS, Js, Scratch, Vbnet, VBA, C, Python He has done Dig Marketing & ranked 2nd on Google in SERP

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.