Table of Contents
Introduction
definition
grammar
algorithm
method
Method 1: Use requests.get() method.
Example
Output
Method 2: Using PyShorteners method
in conclusion
Home Backend Development Python Tutorial Python - URL shortener using Tinyurl API

Python - URL shortener using Tinyurl API

Aug 28, 2023 am 08:53 AM

Python - 使用Tinyurl API的URL缩短器

Introduction

In the Internet age, concise links are crucial for distributing hyperlinks through social networking sites, text messages, and other communication methods. However, URLs that are too long can cause challenges when sharing and can be truncated when sending messages. Long URLs are often difficult to remember and very difficult to type. To solve the current problem, URL shortening platforms like TinyURL were created to manage this task. Python provides a convenient way to connect these options. In this article, we will write a piece of Python code to interact with the TinyURL website API system.

definition

A link shortener is a piece of software that receives a longer URL as data and generates a smaller, more convenient URL. This helps create extended URLs that are easier to exchange and call. When people click on this abbreviated URL, they are forwarded to the real long URL. Link shorteners are widely used on social networking sites, email communications, and any situation where lengthy URLs need to be easily exchanged. These tools shorten extended website links into smaller and more manageable links.

grammar

import requests

url = 'http://tinyurl.com/api-create.php?url='
long_url = 'https://www.example.com/path/to/content/'

response = requests.get(url+long_url)
short_url = response.text

print(short_url)
Copy after login

This code initially imports the module used to make requests to perform requests over HTTP. A variable named "url" holds the base link to the TinyURL application programming interface. This "original_url" variable stores the URL we need to reduce the length of. Next, we make an HTTP request to the TinyURL API using the requests.get() method, passing the entire URL of the API plus the appended extended URL.

Replies from the TinyURL application programming interface will be sent back as text data using the response.text property. This is then assigned to a variable called "short_url". Finally, the code displays the abbreviated URL.

algorithm

  • Step 1: Import the requests module

  • Step 2: Generate the main URL designed for the TinyURL API endpoint

  • Step 3: Set the extension URL that needs to be abbreviated

  • Step 4: Make an HTTP request to the TinyURL service, including the lengthy URL

  • Step 5: Get the compressed URL from the results and display

method

  • Method 1: Use requests.get() method.

  • Method 2: Using PyShorteners method

Method 1: Use requests.get() method.

Example

import requests

def shorten(url):
  base_url = 'http://tinyurl.com/api-create.php?url='
  response = requests.get(base_url+url)
  short_url = response.text
  return short_url

long_url = 'https://www.example.com/path/to/content/'
short_url = shorten(long_url)
print(short_url)
Copy after login

Output

https://tinyurl.com/2jvveeo5
Copy after login

Initially, the code introduces the "requests" module. This module is commonly used with Python to create web requests. This module is used to send queries to the TinyURL interface and get compressed URLs. The script then creates a function called "shorten()". This function accepts a URL as a value and outputs the compact URL. The base URL serves as the starting point for building API requests.

To generate the abbreviated URL, the software sends an HTTP GET call to the TinyURL application programming interface. This process combines "base_url" with the provided parameter "url". The "get()" method of the "requests" module is used to initiate a request by including a constructed URL. The answer to the server query is placed in the "result" variable. To extract the abbreviated URL from the server's response, the code gets the "text" parameter of the response instance. The obtained abbreviated URL is then assigned to the variable denoted "short_url".

This lengthy URL is passed as input to the "shorten()" function. Then use the "print()" command to display the compact URL. If this script is executed, the result is an abbreviated URL obtained from the link shortening API for input "long_url".

The generated compressed URL will be different each time the program is executed. This is because this is a reply based on the link shortener API. You can use an abbreviated URL to direct users to the main extension URL. This makes swapping and retaining much simpler.

Method 2: Using PyShorteners method

Example

import pyshorteners

long_url = 'https://www.example.com/path/to/content/'

s = pyshorteners.Shortener()
short_url = s.tinyurl.short(long_url)
print(short_url)
Copy after login

Output

https://tinyurl.com/abcd123
Copy after login

First, the script imports the "pyshorteners" module file. This module provides a Python package that provides URL shrinking functionality options. This module is used to generate abbreviated URLs. The algorithm then assigns the expanded URL to a variable named "long_url". These are the initial URLs we want to truncate.

This script uses the "is.gd" module to generate new objects of the "Reducer" class. This instance is then set to the variable "s". This object will be used to retrieve the website shortening functionality provided by the toolset.

To create a shortened URL, the algorithm triggers the "compress()" method on the "s.tinyurl" field. The "short()" function accepts an expanded URL as a variable and generates the associated abbreviated URL. In this example, the "long_url" variable is sent as input. The generated shortened URL is recorded in the "short_url" variable.

In summary, this script utilizes the "display()" function to display the compressed URL in the command prompt. If you execute this code, you will get the abbreviated URL created by the "pyshorteners" module corresponding to the given "long_url". Each time the program is executed, the compact URL created will be different. It relies on the program accessing a specific URL shortening service.

The purpose of this program is to show how to quickly generate short URLs from large URLs using the "shortenurl" library. This may be helpful in cases where you want to distribute a short, compact version of the Uniform Resource Locator.

in conclusion

Link shortening has become an important part of contemporary communication. This tool helps create long and complex URLs, making them more manageable and easier to pass around to friends and colleagues. In this learning article, we show how to leverage the Short URL API to compress Python-based URLs. We looked at dual strategies, including full runnable code examples and explanations.

To summarize, this API provides a simple and trustworthy technique to shorten URLs using Python through a simple process. The process can be performed in a short time. Generating shorter URLs is easier than ever by leveraging the Python programming language and TinyURL’s API. By following the demonstration given in this article, any novice programmer can generate a URL shortener using the TinyURL API. People can further integrate these projects into their tasks.

The above is the detailed content of Python - URL shortener using Tinyurl API. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles