How to Make a URL Shortener in Python

Published on Aug. 22, 2023, 12:16 p.m.

To make a URL shortener in Python, you can use an API from a URL shortening service like Bitly or TinyURL. These services allow you to send a request to their API with the original URL, and they will return a shortened URL that you can use instead.

Here’s an example code that uses the requests module to access Bitly API:

import requests

ACCESS_TOKEN = 'your_access_token_here'
url = 'https://api-ssl.bitly.com/v4/shorten'
headers = {
    'Authorization': f'Bearer {ACCESS_TOKEN}',
    'Content-Type': 'application/json',
}
data = {
    'long_url': 'https://www.example.com/very-long-url-that-needs-to-be-shortened',
}
response = requests.post(url, headers=headers, json=data)
if response.ok:
    short_url = response.json()['link']
    print(short_url)
else:
    print('Error:', response.status_code, response.text)

In this example, we first define the Bitly API access token and the URL to access the API. We then define the headers for the request, which includes our access token and the type of data we will be sending. Next, we define the content of our request, which includes the long URL that we want to shorten. We use the requests.post() function to send the request to the Bitly API, and we check if the response is successful using the .ok attribute. If the response is successful, we extract the shortened URL from the JSON response and print it to the console. Otherwise, we print an error message with the HTTP status code and response text.

Note that you need to sign up for a Bitly account and obtain an API access token to use the Bitly API. Also, remember to replace the long_url variable with the URL you want to shorten.

Tags:

related content