<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/" >

<channel>
	<title>URL Shortener &#8211; Dakidarts® Hub</title>
	<atom:link href="https://hub.dakidarts.com/tag/url-shortener/feed/" rel="self" type="application/rss+xml" />
	<link>https://hub.dakidarts.com</link>
	<description>Where creativity meets innovation.</description>
	<lastBuildDate>Sun, 10 Nov 2024 16:38:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://cdn.dakidarts.com/image/dakidarts-dws.svg</url>
	<title>URL Shortener &#8211; Dakidarts® Hub</title>
	<link>https://hub.dakidarts.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Shorten URLs Using Python: Build a URL Shortener Flask API</title>
		<link>https://hub.dakidarts.com/how-to-shorten-urls-using-python-build-a-url-shortener-flask-api/</link>
					<comments>https://hub.dakidarts.com/how-to-shorten-urls-using-python-build-a-url-shortener-flask-api/#respond</comments>
		
		<dc:creator><![CDATA[Dakidarts]]></dc:creator>
		<pubDate>Sun, 10 Nov 2024 16:36:50 +0000</pubDate>
				<category><![CDATA[Coding 👨‍💻]]></category>
		<category><![CDATA[How To 👨‍🏫]]></category>
		<category><![CDATA[Python 🪄]]></category>
		<category><![CDATA[Flask API]]></category>
		<category><![CDATA[how to]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[URL Shortener]]></category>
		<guid isPermaLink="false">https://hub.dakidarts.com/?p=10173</guid>

					<description><![CDATA[Discover how to build a URL shortener in Python with our comprehensive guide. Learn how to set up a Flask API, test it using cURL, Postman, and browser scripts, and create easy-to-share links for social media and more.]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">



<p class="wp-block-paragraph">In this tutorial, we’ll explore a quick and efficient way to create shortened URLs in <a href="https://hub.dakidarts.com/tag/python/">Python</a>, a handy solution for sharing long links on social media, emails, or text messages. </p>



<p class="wp-block-paragraph">Plus, we&#8217;ll go the extra mile and package it as a simple Flask <a href="https://shop.dakidarts.com/product/custom-api-development/" target="_blank" rel="noopener">API</a>, allowing users to shorten URLs on the fly!</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img  decoding="async"  src="https://res.cloudinary.com/ds64xs2lp/image/upload/v1731256366/shortAnimate_crwj4j.gif"  alt="How to Shorten URLs Using Python: Build a URL Shortener Flask API"  title="How to Shorten URLs Using Python: Build a URL Shortener Flask API" ></figure>
</div>


<h2 id="why-use-a-url-shortener" class="wp-block-heading">Why Use a URL Shortener?</h2>



<p class="wp-block-paragraph">Long URLs can look messy and take up a lot of space, especially on platforms with character limits. A URL shortener can:</p>



<ul class="wp-block-list">
<li>Improve link appearance and readability.</li>



<li>Track link clicks for analytics.</li>



<li>Simplify sharing on social platforms and in messages.</li>
</ul>



<p class="wp-block-paragraph"><strong>Common Use Cases:</strong></p>



<p class="wp-block-paragraph">Simplified URLs for mobile sharing or <a href="https://hub.dakidarts.com/how-to-generate-qr-codes-using-python-step-by-step-guide-flask-api-bonus/" data-type="post" data-id="10131">QR codes</a></p>



<p class="wp-block-paragraph">Marketing and promotional links</p>



<p class="wp-block-paragraph">Trackable social media links</p>



<h2 id="setting-up-the-project-environment" class="wp-block-heading">Setting Up the Project Environment</h2>



<p class="wp-block-paragraph">We&#8217;ll use the <code data-enlighter-language="generic" class="EnlighterJSRAW">pyshorteners</code> library to handle URL shortening easily. First, install the required libraries:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install pyshorteners flask</pre>



<h2 id="creating-the-url-shortening-script-in-python" class="wp-block-heading">Creating the URL Shortening Script in Python</h2>



<p class="wp-block-paragraph">The <code data-enlighter-language="generic" class="EnlighterJSRAW">pyshorteners</code> library offers a streamlined way to shorten URLs using various services (e.g., TinyURL, Bitly). Here’s how to shorten a URL:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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))</pre>



<h2 id="building-a-flask-api-for-url-shortening" class="wp-block-heading">Building a Flask API for URL Shortening</h2>



<p class="wp-block-paragraph">We’ll now create a Flask API that takes a URL as input and returns a shortened version.</p>



<h4 id="initialize-the-flask-app" class="wp-block-heading">Initialize the Flask App:</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)</pre>



<h4 id="testing-the-flask-api" class="wp-block-heading">Testing the Flask API</h4>



<p class="wp-block-paragraph">Once the Flask API is up and running, you can test it in a few different ways:</p>



<p class="wp-block-paragraph">1. Using <strong>cURL</strong>:</p>



<p class="wp-block-paragraph">To shorten a URL via <code data-enlighter-language="generic" class="EnlighterJSRAW">cURL</code>, open your terminal and execute the following command:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">curl -X POST http://127.0.0.1:5000/shorten -H "Content-Type: application/json" -d '{"url": "https://example.com/some/very/long/url"}'</pre>



<p class="wp-block-paragraph">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:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
    "short_url": "https://tinyurl.com/xyz123"
}</pre>



<p class="wp-block-paragraph">2. Using a <strong>Web Browser and API Testing Tools</strong></p>



<p class="wp-block-paragraph">If you prefer not to use the terminal, you can test the API using a browser extension like <strong>Postman</strong> or <strong>Insomnia</strong>. Here’s how:</p>



<p class="wp-block-paragraph"><strong>Postman Setup</strong>:</p>



<p class="wp-block-paragraph">Paste the JSON body:</p>



<p class="wp-block-paragraph">Open Postman and create a new POST request.</p>



<p class="wp-block-paragraph">Enter <code data-enlighter-language="generic" class="EnlighterJSRAW">http://127.0.0.1:5000/shorten</code> as the request URL.</p>



<p class="wp-block-paragraph">In the &#8220;Body&#8221; tab, select &#8220;raw&#8221; and choose &#8220;JSON&#8221; from the dropdown menu.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
    "url": "https://example.com/some/very/long/url"
}</pre>



<p class="wp-block-paragraph">Click <strong>Send</strong> to see the API&#8217;s response, which will contain the shortened URL.</p>



<p class="wp-block-paragraph">3. Accessing the API from a <strong>Web Browser Script</strong></p>



<p class="wp-block-paragraph">You can even use JavaScript to test the API by running this code in the browser’s console:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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));
</pre>



<p class="wp-block-paragraph">This script sends a POST request to the API and logs the shortened URL to the console.</p>



<p class="wp-block-paragraph">The API will respond with a JSON object containing the shortened URL.</p>



<h2 id="expanding-the-project" class="wp-block-heading">Expanding the Project</h2>



<p class="wp-block-paragraph"><strong>Analytics</strong>: Track the number of times each shortened URL is accessed.</p>



<p class="wp-block-paragraph"><strong>Custom URL Shortening</strong>: Use services like Bitly or set up your own custom domain for shortened URLs.</p>



<p class="wp-block-paragraph"><strong>Database Storage</strong>: Use a database to keep track of original URLs and their shortened versions.</p>



<h3 id="conclusion" class="wp-block-heading">Conclusion</h3>



<p class="wp-block-paragraph">Creating a URL shortener in Python is a fantastic way to learn about <a href="https://shop.dakidarts.com/product/custom-api-development/" target="_blank" rel="noopener">API development</a> while building a useful tool. </p>



<p class="wp-block-paragraph">This method can be expanded to create custom URL shorteners or analytics-backed services!</p>



<p class="wp-block-paragraph"><a href="https://shop.dakidarts.com/product-category/downloads/ebook/" class="dws-sgp-ls" target="_blank" rel="noopener">
<img  decoding="async"  src="https://res.cloudinary.com/ds64xs2lp/image/upload/v1758338082/X-cover_ptewri.jpg"  alt="Discover Books By our founder Etuge Anselm."  title="How to Shorten URLs Using Python: Build a URL Shortener Flask API" >
</a>
]]></content:encoded>
					
					<wfw:commentRss>https://hub.dakidarts.com/how-to-shorten-urls-using-python-build-a-url-shortener-flask-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<media:content url="https://i3.wp.com/res.cloudinary.com/ds64xs2lp/image/upload/v1731254727/How-to-Shorten-URLs-Using-Python_vtggac.jpg?ssl=1" medium="image"></media:content>
            	</item>
	</channel>
</rss>
