Search code examples
python-3.xpython-requestsurlencode

python3 requests use quote instead of quote_plus


I use Python 3 and the requests module/library for querying a REST service.

It seems that requests by default uses urllib.parse.quote_plus() for urlencoding, i.e. spaces are converted to +.

However the REST service I query misinterpretes this as and. So I need to encode spaces as %20, i.e. use urllib.parse.quote() instead.

Is there an easy way to do this with requests? I couldn't find any option in the documentation.


Solution

  • It turns out you can!

    from requests.utils import requote_uri
    url = "https://www.somerandom.com/?name=Something Cool"
    requote_uri(url)
    
    'https://www.somerandom.com/?name=Something%20Cool'
    

    documentation here The requote_uri method is about halfway down the page.