python requests query params encoding

Python Requests Query Params Encoding

If you are working with APIs that require query parameters, you need to make sure that they are encoded properly. Python requests library provides a convenient way to add query parameters to your requests.

The params parameter in the requests library is used to pass query parameters. It can be a dictionary or a list of tuples. When you pass a dictionary, requests will automatically encode the keys and values in the URL format. However, when you pass a list of tuples, you need to manually encode the values.


import requests
import urllib.parse

# Using dictionary
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://example.com/api', params=params)

# Using list of tuples
params = [('key1', 'value1'), ('key2', 'value2')]
encoded_params = urllib.parse.urlencode(params)
response = requests.get('https://example.com/api?' + encoded_params)

In the above example, we are using both dictionary and list of tuples to pass query parameters. When we pass a dictionary, requests library automatically encodes it for us. However, when we pass a list of tuples, we need to manually encode it using urllib.parse.urlencode method.

Encoding Types

There are different types of encoding methods that can be used while encoding query parameters. The default encoding method is utf-8. However, if you want to use a different encoding method, you can specify it using the encoding parameter.


import requests

params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://example.com/api', params=params, encoding='ISO-8859-1')

In the above example, we are using ISO-8859-1 encoding method instead of default utf-8 encoding method.

Conclusion

Proper encoding of query parameters is important while working with APIs. Python requests library provides a convenient way to add query parameters and automatically encodes them for us. However, when we pass a list of tuples, we need to manually encode the values. We can also specify different encoding methods if required.