Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 695
Gilbert Williams Avatar asked Oct 22 '25 23:10

Gilbert Williams


2 Answers

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.
like image 186
lepsch Avatar answered Oct 24 '25 12:10

lepsch


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

like image 21
Santhosh Urumese Avatar answered Oct 24 '25 13:10

Santhosh Urumese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!