Gilbert Williams
Gilbert Williams

Reputation: 1050

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?

Upvotes: 4

Views: 9656

Answers (3)

lepsch
lepsch

Reputation: 10319

You cannot pass null values with the requests 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.

Upvotes: 4

Xiddoc
Xiddoc

Reputation: 3628

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

Upvotes: 1

Santhosh Urumese
Santhosh Urumese

Reputation: 171

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

Upvotes: 1

Related Questions