5

I am writing a Python wrapper for an API that supports the query parameters that have values (e.g. param1 below) and query parameters that do not have values value (e.g. param2 below) i.e.

https://example.com/service?param1=value1&param2

The HTTP requests library famously supports parameters with values and parameters without values. However I need to be able to specify both types of parameters.

1 Answer 1

9

You have two options with Requests in terms of the query string: 1) provide key/value pairs by way of a dictionary, or 2) provide a string. If you provide #1, you'll always get a '=' for each key/value pair...not what you want. So you have to use #2, which will let you do whatever you want, since it will just include what you give it as the entire query string. The downside is that you have to construct the query string yourself. There are many ways of doing that, of course. Here's one way:

params = {'param1': 'value1', 'param2': None}
params = '&'.join([k if v is None else f"{k}={v}" for k, v in params.items()])
r = requests.get('https://example.com/service', params=params)
print(r.url)

This way lets you supply a dictionary, just like if you were letting Requests build the query string, but it allows you to specify a value of Null to indicate that you want just the key name, with no '='. Requests will normally not include the parameter at all if its value is None in the dictionary.

The result of this code is exactly what you gave as an example of what you want:

https://example.com/service?param1=value1&param2
Sign up to request clarification or add additional context in comments.

1 Comment

and how do I retrieve param2 on receiving end from the request string? basically to check whether it exist or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.