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)
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)
Output
https://tinyurl.com/2jvveeo5
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)
Output
https://tinyurl.com/abcd123
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!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use