Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URI encoding in Python Requests package

Tags:

I am using python requests package to get results from a API and the URL contains + sign in it. but when I use requests.get, the request is failing as the API is not able to understand + sign. how ever if I replace + sign with %2B (URI Encoding) the request is successful.

Is there way to encode these characters, so that I encode the URL while passing it to the requests package

Error: test [email protected] does not exist API : https://example.com/[email protected] 
like image 749
user3435964 Avatar asked Oct 17 '17 05:10

user3435964


People also ask

How do you encode a URI component in Python?

You can encode multiple parameters at once using urllib. parse. urlencode() function. This is a convenience function which takes a dictionary of key value pairs or a sequence of two-element tuples and uses the quote_plus() function to encode every value.

Does Python request encode URL?

In Python, we can URL encode a query string using the urlib. parse module, which further contains a function urlencode() for encoding the query string in URL. The query string is simply a string of key-value pairs.

How do you pass special characters in a URL in Python?

s = urllib2. quote(s) # URL encode. # Now "s" is encoded the way you need it. It works!

What does URI encoding do?

The encodeURI() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).


1 Answers

You can use requests.utils.quote (which is just a link to urllib.parse.quote) to convert your text to url encoded format.

>>> import requests >>> requests.utils.quote('[email protected]') 'test%2Buser%40gmail.com' 
like image 174
MohitC Avatar answered Sep 30 '22 14:09

MohitC