Requests URL Encoding in Python

In this blog, we are trying to teach our users how they can requests URL encoding in python. When calling a remote API with additional query strings or path arguments, URL encoding is frequently required. The URL must be properly URL encoded for any query string or path parameter. While preparing data for submission, URL encoding is also necessary. 

 

 

 

Method of requests URL encoding in python

The quote() function offered by the urllib.parse package must be used to URL encode any string in order to resolve this problem. The UTF-8 encoding system is the default for the quote() function.

 

import urllib.parse
query = 'Study Experts'
# parsing the quote 
urllib.parse.quote(query)
'Stu%C3%B6%20Ex%C3%B6rld%40perts'

 

Output

 

Keep in mind that the quote() function by default deems the / character to be safe. It doesn’t encode or characterize. Safe is a named argument that the quote() method accepts, and its default value is /. By entering an empty string in the safe argument, you can encode / character and other data as well. One interesting fact is that one can also encode more than one parameter as well. 

 

 

import urllib.parse
params = {'q': 'Python URL encoding', 'as_sitesearch': 'www.studyexperts.in'}
# parsing multiple characters using urlencode
urllib.parse.urlencode(params)
'q=Python+URL+encoding&as_sitesearch=www.studyexperts.in'

 

Output

 

 

If you want the quote() function to be used for encoding parameters by the urlencode() function. A parameter called doseq is an optional argument for the urlencode() method. Set the doseq argument to True if your input accepts multiple values for a single key in order to appropriately encode all the data.

 

 

 

Also Read: Python Botocore

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *