Reqwest params with get request

I'm trying to insert some required params to a call to a particular API, but the params are not being appropriately incorporated into the URL.

This works:

fn main() ->  Result<(), Box<dyn std::error::Error>> {
    let url_full = "https://holidayapi.com/v1/holidays?key=<my-api-key>&country=US&year=2020";
    let client = reqwest::blocking::Client::new();
    let res = client.get(url_full).send()?;

    println!("holidays = {:#?}", res.text().unwrap());

    Ok(())
}

This does not work:

fn main() ->  Result<(), Box<dyn std::error::Error>> {
    let url = "https://holidayapi.com/v1/holidays";
    let api_key = "<my-api-key>";
    let params = [
        ("key", api_key),
        ("country", "US"),
        ("year", "2020")
    ];
    let client = reqwest::blocking::Client::new();
    let res = client.get(url)
        .form(&params)
        .send()?;

    println!("holidays = {:#?}", res.text().unwrap());

    Ok(())
}

The server responds with a 401 error stating that an API key parameter is required. I cannot find the link now, but I know there is an example that shows this format somewhere in the reqwest docs.

2 Likes

In the second case, you're trying to do GET request with data placed in request body. If you change client.get to client.post, will it work?

You can use Url::parse_with_params:

fn main() ->  Result<(), Box<dyn std::error::Error>> {
    let url = "https://holidayapi.com/v1/holidays";
    let api_key = "<my-api-key>";
    let params = [
        ("key", api_key),
        ("country", "US"),
        ("year", "2020")
    ];
    let url = reqwest::Url::parse_with_params(url, &params)?;
    let res = reqwest::blocking::get(url)?;

    println!("holidays = {:#?}", res.text().unwrap());

    Ok(())
}
4 Likes

Nice...thank you!

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.