How to Setup an Automated Bitly URL-shortener in Python in 3 Easy Steps

What will we cover in this tutorial?

  • To get you started from scratch to use Bitly in Python.
  • How to register at Bitly and get your Authentication token to access the Bitly API v4.
  • To get the Python library to connect to the API.
  • A walk-through of the API functionality available.

Step 1: Register at Bitly and get your Access Token

The first thing you need is to register at Bitly to use their functionality.

You can do that be follow this link.

Press the Sign up at Bitly

You should press the Sign up at the right upper corner.

Scroll down and press the Get Started for Free.

Press Get Started for Free

Then fill out the fields with your preferred credentials.

Fill out with your credentials

You should receive an email in the inbox of the email address you provided. Click the link in that email.

You should be forwarded to Bitly and then you should find your profile settings.

When clicking the Profile Settings you should find the Generic Access Token.

You will be asked to fill out your password, then press Generate Token.

Then you should get an access token like this one (this one is not valid, so you cannot use it):


Step 2: The URL-shortener library in Python

Luckily someone else did all the complicated work to use the Bitly API. All you need to do in Python is to get the library. The library is called pyshortener, which is a library to wrap and consume the most used shorteners APIs. Hence, you can use it with many URL shorteners. Please notice, that the access token you have generated in this tutorial is only valid for Bitly.

To install that library simply type the following command in your shell.

pip install pyshortener

You get a full list of the supported URL-shorteners in their documentation.

Step 3: Use the URL-shortener library

You get access to your URL-shortener functionality at Bitly by the following setup.

import pyshorteners
s = pyshorteners.Shortener(api_key='YOUR_KEY')

You should obviously use replace ‘YOUR_KEY’ with the key you obtained in Step 1.

Then you can create a Bitly shortened URL with the following call.

import pyshorteners

s = pyshorteners.Shortener(api_key=ACCESS_TOKEN)
url = s.bitly.short("")

Which in my example gave me the following link.

This should also populate your web API at Bitly.

You can also retrieve how many clicks have been made on your link.

import pyshorteners

s = pyshorteners.Shortener(api_key=ACCESS_TOKEN)
clicks = s.bitly.total_clicks("")

Which in this case (surprisingly) returned 0 clicks.

Finally, you can also expand on a URL you already created a Bitly link on.

import pyshorteners

s = pyshorteners.Shortener(api_key=ACCESS_TOKEN)
expand = s.bitly.expand("")

Which will result in the URL you created it with.

That is it. See the full documentation of it here of how to use Bitly in Python.