简体   繁体   中英

Python Requests - send null as query params value

My URL can take null as a value for a query param like so:

https:/api.server.com/v1/users/?parent=null

When I'm trying to send the request in Python using Requests, I'm passing None :

requests.get(
    BASE_URL + USER_URL,
    headers = get_headers(),
    timeout = 60,
    params = {
        'parent': None
    }
)

However, it seems to skip the query param parent if it's set to None . How can I force it?

You cannot pass null values with the resquests package as it's the default behavior as stated in the docs:

Note that any dictionary key whose value is None will not be added to the URL's query string.

Some solutions:

  1. Maybe you can assume that not having it at the backend is null , or;
  2. You can pass an empty string, or;
  3. Pass a non-existent ID like 0 / -1 , or;
  4. Pass a boolean param like parent=false or no-parent=true .
  5. I would not recommend passing the string 'null' as it can be interpreted differently depending on the backend framework you're using. But if that's the case you can do so.

As @lepsch has mentioned, the requests library will not add None values to your query parameters. However, I feel like there is a misunderstanding in the entire question.

The URL https:/api.server.com/v1/users/?parent=null does not have the query parameter set to None . It is in fact set to 'null' , which is actually a string with the data "null" inside of it. Therefore, if you want to do this, all you have to do is change None in your request to 'null' :

requests.get(
    BASE_URL + USER_URL,
    headers = get_headers(),
    timeout = 60,
    params = {
        'parent': 'null'
    }
)

# This will request
# https:/api.server.com/v1/users/?parent=null

However, if you want a true null value, then you should consider either putting an empty string value... :

...
params = {
    'parent': ''
}
...

# This will request
# https:/api.server.com/v1/users/?parent=

... or use the actual null encoded character, as described in this answer :

requests.get(
    BASE_URL + USER_URL + "?parent=%00", # Must be added directly, as to not encode the null value
    headers = get_headers(),
    timeout = 60
)

# This will request
# https:/api.server.com/v1/users/?parent=%00

None param will be skipped as if such a param is not set.

import requests

r = requests.get('http://localhost:9090/events', params = { 'param1': None, 'param2':'', 'param3':'param_val' })
print(r.url)

Result: http://localhost:9090/events?param2=&param3=param_val

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM