• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Code Snippets / Bitly Shortener with Python

Bitly Shortener with Python

Author: PFB Staff Writer
Last Updated: December 2, 2020

Before we start

Bitly allows users to shorten, share, and track links (URLs).

It’s a way to save, share and discover links on the web.

Bitly provides public API’s which is intended to make it even easier for
python programmers to use.

First Step

The first step is to head over to dev.bitly.com where you will find the API
documentation, best practices, code libraries, public data sets.

What is an API Key?

Many services on the Internet (such as Twitter, Facebook..) requires that you
have an “API Key”.

An application programming interface key (API key) is a code passed in by
computer programs calling an API to identify the calling program, its developer,
or its user to the Web site.

API keys are used to track and control how the API is being used, for example
to prevent malicious use or abuse of the API.

The API key often acts as both a unique identifier and a secret token for
authentication, and will generally have a set of access rights on the API
associated with it.

Get the Bitly API Key

To be able for us to shorten links (see below) we’ve to sign up for an API key.

The signup procedure is pretty much explaining itself, so I’ll not cover
that in this post.

Create your Bitly API Key here

Bitly Code Libraries

A number of developers have written code libraries to interact with the bitly
API in several different languages. Since we’re programming in Python,
we’re of course interested in the Python libraries.

There are currently three different libraries to choose, which you can find here

In this post we will use the “bitly-api-python” library, which is also the
official Python client.

Bitly API Python

The installation of Bitly API is very easy.


# Installation using PIP

pip install bitly_api
Downloading/unpacking bitly-api
Downloading bitly_api-0.2.tar.gz
Running setup.py egg_info for package bitly-api
Installing collected packages: bitly-api
Running setup.py install for bitly-api
Successfully installed bitly-api
Cleaning up...

Shorten a URL

We want to write a script that will reduce the URL length to make the sharing
easier. Open up your favourite text editor and put in the code below.

Save the file as shortener.py

#!/usr/bin/env python

# Import the modules

import bitlyapi
import sys

# Define your API information

API_USER = "your_api_username"
API_KEY = "your_api_key"

b = bitlyapi.BitLy(API_USER, API_KEY)

# Define how to use the program

usage = """Usage: python shortener.py [url]
e.g python shortener.py http://www.google.com"""

if len(sys.argv) != 2:
    print usage
    sys.exit(0)

longurl = sys.argv[1]

response = b.shorten(longUrl=longurl)

print response['url']

Shortener.py Explained

We started the program with #!/usr/bin/env python

#!/usr/bin/env python

Importing the modules that we’re going to use in our program

import bitlyapi
import sys

Defining our API information

API_USER = "your_api_username"
API_KEY = "your_api_key"
b = bitlyapi.BitLy(API_USER, API_KEY)

Defining how to use the the program

usage = """Usage: python shortener.py [url]
e.g python shortener.py http://www.google.com"""

if len(sys.argv) != 2:
    print usage
    sys.exit(0)

Creates a variable longurl and sets the value to the argument passed in

longurl = sys.argv[1]

Gives the Bitly API the longurlresponse = b.shorten(longUrl=longurl)

Prints out the the URL value

print response['url']

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: bitly, Code Snippets Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary โ€“ How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 ยท PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us