requests icon indicating copy to clipboard operation
requests copied to clipboard

URL parameter is added when the value is an empty string but not when it is an empty list

Open Lalee10 opened this issue 1 year ago • 2 comments

Both an empty string '' and an empty list [] are not of NoneType and are considered a falsy value and therefore should behave the same when being added as a URL parameter. But in requests when passing an empty string '' as a parameter value the final URL contains the parameter but not when an empty list [] is passed as the value.

Expected Result

When passing an empty list as parameter value, the final URL should contain the parameter.

Actual Result

When passing an empty list as parameter value, the final URL does not contain the parameter.

Reproduction Steps

import requests

base_url = 'https://jsonplaceholder.typicode.com/todos'

params = {'_limit': 5, 'id__in': ''}
response = requests.get(base_url, params)
print(response.request.url)
# Output: https://jsonplaceholder.typicode.com/todos?_limit=5&id__in=

params = {'_limit': 5, 'id__in': []}
response = requests.get(base_url, params)
print(response.request.url)
# Output: https://jsonplaceholder.typicode.com/todos?_limit=5

System Information

$ python -m requests.help
{
  "chardet": {
    "version": null
  },
  "charset_normalizer": {
    "version": "3.1.0"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "3.4"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.10.11"
  },
  "platform": {
    "release": "22.6.0",
    "system": "Darwin"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.28.2"
  },
  "system_ssl": {
    "version": "1010115f"
  },
  "urllib3": {
    "version": "1.26.15"
  },
  "using_charset_normalizer": true,
  "using_pyopenssl": false

Lalee10 avatar Oct 25 '23 08:10 Lalee10

Yes as observed this is the case when using any other empty datatype, except a str(), as it gives an empty string.

From Documentation: " Note that any dictionary key whose value is None will not be added to the URL’s query string. "

But as known, an empty list is not of None type, so i guess since it does not know what to do with empty datatypes it just treats then as None.

Krupakar-Reddy-S avatar Oct 26 '23 06:10 Krupakar-Reddy-S

Proposed a fix here - https://github.com/psf/requests/pull/6561

amkarn258 avatar Oct 30 '23 18:10 amkarn258