Reqwest - how to create a query string with parameters that don't have explicit values

For example, to create https://www.google.com/?foo=bar I can do

use reqwest::Client;

fn main() {
    let client = Client::builder().build().unwrap();
    let req = client.get("https://www.google.com").query(&[("foo", "bar")]).build().unwrap();
    println!("{}", req.url());
}

But how do I create https://www.google.com/?foo? (notice the missing =bar). And yes, these URIs are valid: stackoverflow question and answer.

I know I can create it with direct string manipulation, but I want to know if it's possible to create using the RequestBuilder or URL methods provided in the library.

Currently you cannot through reqwest's API, there is no code path that calls through to form_urlencoded::Serializer::append_key_only. Note there is an intermediate serde_urlencoded crate that needs to also be updated to call through to form_urlencoded if you want to add support.

If you depend on form_urlencoded directly (because it's not re-exported through reqwest), you can do:

let mut req = client.get("https://www.google.com").build().unwrap();

let query: String = form_urlencoded::Serializer::new(String::new())
    .append_key_only("foo")
    .finish();
req.url_mut().set_query(Some(&query));

But I guess that's not very different from setting it through a String yourself.

Thanks for pointing out where the query string is being serialized. But yes, that becomes so verbose that I might as well simply create the URL from a String.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.