Python

How to urlencode in Python?

Whenever contacting a web API containing extra query strings or route arguments, URL encoding is frequently required. Any query phrase or route argument inside the URL should be URL encrypted correctly. When formulating information for submission using the application/x-www-form-urlencoded MIME format, URL encoding is necessary. You’ll discover how to encrypt URL fragments in Python throughout this article.

Example 01: Use of Quote Function On String

First of all, log in from the Ubuntu 20.04 system and try opening the shell terminal on it. You can open the shell by Ctrl+Alt+T shortcut key. After opening it, you have to create a new python file with any name using the touch instruction below. You can see we have named the file “test.py.”

$ touch test.py

To understand the concept of the encoding URL, we need to understand the concept of encoding a string first. Hence in this example, we will see how to encode a string. Your newly created file is located in the home directory of your system. Hence, open the file explorer and navigate towards the home directory. Open the newly created file by double-clicking on it. Write the code shown below in your file and save it. You can see this code contains the python-support at its first line. After that, you need to import a “urllib” library required to encode any URL. You can see we have imported the class “parse” from this library as well. This is to use the functions that it occupies for the parsing of any string. After that, we have defined a string named “str” with some string value in it. Then we have used the “quote” function utilizing parse class and “urllib” to encode the variable “str” value and save it into a new variable, “new.” On the fifth line, we have printed the encoded string “new.”

#!/usr/bin/python
import urllib.parse
str = "HY! MY name is Aqsa Yasin."
new = urllib.parse.quote(str)
print(new)

Execution of this file takes place at the terminal via the python3 query as below. The output result is showing the encoding of a string successfully.

$ python3 test.py

Example 02: Use of Urlencode Function On String

In the above example, you have seen that we have used the quote() function to encode or quote a string-type variable, and it worked perfectly. On the other hand, you need to understand that we cannot apply the “urlencode” method on any string because the string cannot be encoded into any URL. Let’s have a look at this for once. Open the same file again and update the code as below. You have just to change the function from “quote” to “urlencode” in this code. All the remaining statements are the same. Save your file and close it.

#!/usr/bin/python
import urllib.parse
str = "HY! MY name is Aqsa Yasin."
new = urllib.parse.urlencode(str)
print(new)

To run the file, use the stated-below query in your command-shell of the Ubuntu system. After running the python file, we have encountered an exception of “TypeError.” This means the function “urlencode” cannot be applied to the string type variable at any cost.

$ python3 test.py

Example 03: Use of Urlencode Function On Dictionary

From the above two examples, we have understood that to apply the urlencode function; we must have some other type variable for this. Hence open the same file test.py from the home folder of the Linux system. After opening it, update it with the script shown in the small snapshot image beneath. We have added the same library, “urllib,” and imported its parse class along with it. Then we have declared a list dictionary with 2 keys and 2 values. Then we have used this dictionary in the parenthesis of the function “urlencode” of a class parse and package urllib to encode it into a URL format. This encoded URL will then saved into a variable “new” and printed out on the terminal by a print statement at line 5. You can save the python file by click on the Save button at the top of a file or simply using “Ctrl+S.” After saving it, click on the “Cross” sign on the right side of the file window to close it.

#!/usr/bin/python
import urllib.parse
l = { "Name": "Aqsa", "SurName": "Yasin"}
new = urllib.parse.urlencode(1)
print(new)

Let’s execute our python file once again by a stated-below instruction. The resultant output is showing the encoded format of a dictionary. It is showing clearly that the “Name” of a person is “Aqsa,” separating by the “=” sign. Also, it is separating One key value from another, e.g., Name and Surname.

$ python3 test.py

Example 04: Use of Urlencode On Multiple-Valued Dictionary

Open the test.py file and update the code with the below script. This time we have been using the multiple-type value dictionary list in our code. You can see clearly that the dictionary contains a list as a value in it. Now we will see how the “urlencode” method works on it. We have used the dictionary “l” in the parameter of a “urlencode” method with “doseq” value as “True” to avoid special characters in our output. After that, we have printed the encoded value. Save your file using “Ctrl+S” and hit the cross button on the right corner of the file window to quit it.

#!/usr/bin/python
import urllib.parse
l = { 'Name': 'Aqsa', 'Salary': [ 50000, 80000]}
new = urllib.parse.urlencode(l, doseq=True)
print(new)

Let’s execute the file to see the working of the urlencode method by a query stated-beneath. The output shows that the encoded value shows the two separate values for the key “Salary.” This means urlencode works correctly on multitype dictionary lists.

$ python3 test.py

Example 05: Use of Urlencode On Dictionary

This time we will be using a URL as a value to a dictionary key. So, open the file “test.py” and update its code with the below-shown one. You can see we have used the URL as a value to key.

#!/usr/bin/python
import urllib.parse
str = {'The encoded': 'url is', 'this =': 'www.aiou.gov.pk'}
new = urllib.parse.urlencode(str)
print(new)

Execution of this code shows us the encoded version of dictionary contents.

$ python3 test.py

Conclusion:

We have done almost all possible examples of the “urlencode” method in our guide. Hope you will find no error while implementing these examples.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.