Where creativity meets innovation.

+237 671568238

Have a question, comment, or concern? We're ready to hear and assist you. Reach us through our social media, phone, or live chat.

How to Shorten URLs Using Python: Build a URL Shortener Flask API

How to Shorten URLs Using Python: Build a URL Shortener Flask API

In this tutorial, we’ll explore a quick and efficient way to create shortened URLs in Python, a handy solution for sharing long links on social media, emails, or text messages.

Plus, we’ll go the extra mile and package it as a simple Flask API, allowing users to shorten URLs on the fly!

How to Shorten URLs Using Python: Build a URL Shortener Flask API

Why Use a URL Shortener?

Long URLs can look messy and take up a lot of space, especially on platforms with character limits. A URL shortener can:

  • Improve link appearance and readability.
  • Track link clicks for analytics.
  • Simplify sharing on social platforms and in messages.

Common Use Cases:

Simplified URLs for mobile sharing or QR codes

Marketing and promotional links

Trackable social media links

Setting Up the Project Environment

We’ll use the pyshorteners library to handle URL shortening easily. First, install the required libraries:

pip install pyshorteners flask

Creating the URL Shortening Script in Python

The pyshorteners library offers a streamlined way to shorten URLs using various services (e.g., TinyURL, Bitly). Here’s how to shorten a URL:

import pyshorteners
def shorten_url(long_url):
    s = pyshorteners.Shortener()
    short_url = s.tinyurl.short(long_url)
    return short_url
# Example usage:
long_url = "https://example.com/some/very/long/url"
print("Shortened URL:", shorten_url(long_url))

Building a Flask API for URL Shortening

We’ll now create a Flask API that takes a URL as input and returns a shortened version.

Initialize the Flask App:

from flask import Flask, request, jsonify
import pyshorteners
app = Flask(__name__)
# URL shortening function
def shorten_url(long_url):
    s = pyshorteners.Shortener()
    return s.tinyurl.short(long_url)
# Flask route for URL shortening
@app.route('/shorten', methods=['POST'])
def api_shorten_url():
    data = request.json
    long_url = data.get("url")
    if not long_url:
        return jsonify({"error": "URL is required"}), 400
    try:
        short_url = shorten_url(long_url)
        return jsonify({"short_url": short_url}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
    app.run(debug=True)

Testing the Flask API

Once the Flask API is up and running, you can test it in a few different ways:

1. Using cURL:

To shorten a URL via cURL, open your terminal and execute the following command:

curl -X POST http://127.0.0.1:5000/shorten -H "Content-Type: application/json" -d '{"url": "https://example.com/some/very/long/url"}'

This command sends a POST request to the API endpoint with a JSON payload containing the URL you want to shorten. If the request is successful, you’ll see a JSON response similar to this:

{
    "short_url": "https://tinyurl.com/xyz123"
}

2. Using a Web Browser and API Testing Tools

If you prefer not to use the terminal, you can test the API using a browser extension like Postman or Insomnia. Here’s how:

Postman Setup:

Paste the JSON body:

Open Postman and create a new POST request.

Enter http://127.0.0.1:5000/shorten as the request URL.

In the “Body” tab, select “raw” and choose “JSON” from the dropdown menu.

{
    "url": "https://example.com/some/very/long/url"
}

Click Send to see the API’s response, which will contain the shortened URL.

3. Accessing the API from a Web Browser Script

You can even use JavaScript to test the API by running this code in the browser’s console:

fetch('http://127.0.0.1:5000/shorten', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ url: 'https://example.com/some/very/long/url' })
})
.then(response => response.json())
.then(data => console.log('Shortened URL:', data.short_url))
.catch(error => console.error('Error:', error));

This script sends a POST request to the API and logs the shortened URL to the console.

The API will respond with a JSON object containing the shortened URL.

Expanding the Project

Analytics: Track the number of times each shortened URL is accessed.

Custom URL Shortening: Use services like Bitly or set up your own custom domain for shortened URLs.

Database Storage: Use a database to keep track of original URLs and their shortened versions.

Conclusion

Creating a URL shortener in Python is a fantastic way to learn about API development while building a useful tool.

This method can be expanded to create custom URL shorteners or analytics-backed services!

How to Shorten URLs Using Python: Build a URL Shortener Flask API
Share this article
Shareable URL
Prev Post

How To Remove Image Background Using Python: Step-by-Step Guide with Flask API

Next Post

Microsoft and OpenAI: A Strategic Partnership on the Horizon

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Read next
0
Would love your thoughts, please comment.x
()
x