Using hyper: how to get URL query string params?

#1

Given a GET url: http://example.com/data?key1=value1&key2=value2, I can get the “query part” via

let params = request.uri().query().unwrap();
// params = "key1=value1&key2=value2"

But, how do I get the values of key1 and key2? Is splitting the string by “&” and then by “=” the only way?
I looked at https://docs.rs/hyper/0.12.19/hyper/struct.Uri.html#method.query, but it didn’t help.

1 Like
#2

Hyper does not have a built-in method to do that. However, the url crate has the url::Url::query_pairs() method and it’s already a dependency of hyper, so you won’t need to download anything new.
To convert a Uri from hyper into a Url from url, use url::Url::parse(&request.uri().to_string()) (returns a Result).

In your example, the code would be

let uri_string = request.uri().to_string();
let request_url = Url::parse(&uri_string).unwrap();
let params = request_url.query_pairs();

// or:
let params = Url::parse(&request.uri().to_string()).unwrap().query_pairs();

This method returns an Iterator of (key, value) pairs. So you can collect it into a Vector with params.collect() or you can iterate over it with for param in params { /* ... */ }. Or use any Iterator methods

Note: Hyper did have a Request::query_pairs but in 0.11 they removed it for some reason. I could not find anything related to that change in the changelog of 0.11.