How to percent-encode URL parameters in Python?

Estimated read time 2 min read

To percent-encode URL parameters in Python, you can use the urllib.parse module. Specifically, the urlencode() function can be used to encode a dictionary of key-value pairs as a query string, which can then be appended to the URL.

Here’s an example:

import urllib.parse

params = {'name': 'John Doe', 'email': 'john@example.com'}
encoded_params = urllib.parse.urlencode(params)
url = 'https://example.com/api?' + encoded_params

print(url)

In this example, we first create a dictionary called params containing two key-value pairs representing the user’s name and email address. We then use the urlencode() function to encode the dictionary as a query string, which we store in the encoded_params variable.

We then concatenate the encoded query string with the base URL of the API endpoint to create the final URL. Finally, we print the URL to the console.

The urlencode() function automatically percent-encodes the parameter values, as well as any special characters in the parameter keys (such as spaces). The resulting query string is safe to use in a URL.

You can customize the encoding behavior of the urlencode() function by passing in additional arguments. For example, you can change the separator character between key-value pairs using the separator argument.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply