Explain Codes LogoExplain Codes Logo

How to urlencode a querystring in Python?

python
urlencode
querystring
url-encoding
Alex KataevbyAlex Kataev·Dec 4, 2024
TLDR

Enact URL encoding in Python by utilizing urlencode from urllib.parse. Simply pass a dictionary of your parameters to urlencode():

from urllib.parse import urlencode params = {'key': 'value', 'phrase': 'hello world'} print(urlencode(params)) # Prints: "key=value&phrase=hello+world"

The output in Python 2 can be achieved by substituting urllib.parse with urllib. Pretty neat, huh?

Special characters: A pesky little detail

Special characters and spaces motivating you for a mid-life career change? Fear not! We have quote_plus in our toolbox. It’s from the urllib.parse library and she’s a real gem when dealing with spaces.

from urllib.parse import quote_plus param_value = "hello world" # Classic phrase, love the space! safe_param = quote_plus(param_value) print(safe_param) # Prints: "hello+world"

Do you hear that? That's the sound of special characters causing zero problems.

For those who value order and individuality

Is the order of your parameters of utmost importance? Do certain parameters have multiple values? We've got a list of tuples for that:

from urllib.parse import urlencode ordered_params = [('key', 'value1'), ('key', 'value2'), ('another_key', 'another_value')] print(urlencode(ordered_params)) # Prints: "key=value1&key=value2&another_key=another_value"

Feels good being in control.

The Lazy Programmer's Guide: Use the Requests library

The Requests library takes a load off your shoulders by handling the encoding through a direct params pass:

import requests response = requests.get('http://example.com', params={'key': 'value with spaces', 'phrase': 'hello world'}) print(response.url) # Who needs manual encoding, right?

Your params dictionary is transformed into a query string without the agony of manual encoding. Slick!

To encode, or to quote_plus?

Choice paralysis between urlencode and quote_plus? Here's what you should know to break the deadlock:

Use urlencode when dealing with a dictionary or list of tuples. It handles keys and values like a pro, making sure everything's encoded.

Use quote_plus when encoding individual values, particularly if they include spaces. Silent hero for spaces!

Give your encoded output a once-over to confirm it aligns with your URL structure expectations.

Customize to your heart's desire

Custom encoding stratagems for specific characters can be implemented using granular functions within urllib.parse or even build your own encoder. Play the master coder you were born to be!

Seal it tight with encoding

Beyond complying with standards, encoding is integral for security, keeping injection attacks at bay and assuring that user-generated content doesn't create havoc with your URLs or backend processing. No one likes a 2am system failure.