Build query string with param having multiple values for a reqwest Client

Viewed 631

I'm trying to build a query string for reqwest Client using the builder's query() method. But one of the parameters has to be multiple values encoded like this

 ?dt=t&dt=at&dt=m

I can't figure out how.

use reqwest::blocking::Client;
use serde_json::{json, Value as JsonValue};


fn main() {
    let query = json!({
        "client": "gtx",
        "ie": "UTF-8",   // input encoding
        "oe": "UTF-8",   // output encoding
        "sl": "auto",    // source language
        "tl": "en",      // target language
        "dt": ["t", "at", "m"],  // <<<<< ERROR
        "q": "salut les gars. ca va? on y va!",       // text to translate
    });
    let client = Client::new();
    let response = client.get("https://translate.googleapis.com/translate_a/single")
                         .query(&query)
                         .send()
                         .unwrap();
    if response.status().is_success() {
        let body: JsonValue = response.json().unwrap();
        println!("detected language {:}", body.get(2).unwrap());

        for item in body.get(0).and_then(JsonValue::as_array).unwrap() {
            println!("{:}", item[1]);
            println!("{:}", item[0]);
        }
    } else {
        println!("fail {:?}", response);
    }
}


 reqwest::Error { kind: Builder, source: Custom("unsupported value") }

Maybe it's not supported? I guess I can just build the string manually with format! as a last resort

2 Answers

You can build your query arguments as an IntoIterator of key-value pairs instead.

For example,

let query = vec![
    ("client", "gtx"),
    ("ie", "UTF-8"),   // input encoding
    ("oe", "UTF-8"),   // output encoding
    ("sl", "auto"),    // source language
    ("tl", "en"),      // target language
    ("dt", "t"),
    ("dt", "at"),
    ("dt", "m"),
    ("q", "salut les gars. ca va? on y va!"), // text to translate
];

let client = Client::new();
let response = client.get("https://translate.googleapis.com/translate_a/single")
                     .query(&query)
                     .send()

I am not familiar with Rust, but the query structure must be like this:

?dt[]=t&dt[]=at&dt[]=m

Otherwise you are just overwriting the variable.

in PHP you have the http_query_builder for that. Maybe this will bring you in the right direction: https://docs.rs/querystring/latest/querystring/ ?

Related