Search code examples
rustreqwest

Why get method is not returning a Response object in reqwest?


I'm trying to replicate an example from reqwest documentation. Here is the example:

let body = reqwest::get("https://www.rust-lang.org")?
.text()?;

After I have added the reqwest = "0.10.10" line in the file Cargo.toml, I add the following code in my main.rs file:

extern crate reqwest;

fn main() {
    let body = reqwest::get("https://www.rust-lang.org")?.text()?;
    println!("body = {:?}", body);
}

This code don't compile and returns the following error:

cannot use the `?` operator in a function that returns `()`

I'm a bit surprised with this behaviour since my code is almost ipsis litteris the documentation code.

I think that ? works only on Response objects, so I checked which object the get method is returning:

extern crate reqwest;

fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}

fn main() {
    let body = reqwest::get("https://www.rust-lang.org");
    print_type_of(&body);
}

output:

core::future::from_generator::GenFuture<reqwest::get<&str>::{{closure}}

I mean, why I'm not getting an Response object instead, just like the documentation?


Solution

  • There are two separate issues here tripping you up.

    The documentation that you've linked to is for reqwest version 0.9.18, but you've installed version 0.10.10. If you look at the docs for 0.10.10, you will see that the snippet you use is

    let body = reqwest::get("https://www.rust-lang.org")
        .await?
        .text()
        .await?;
    
    println!("body = {:?}", body);
    

    or more likely in your case, since you have not mentioned having an async runtime, the blocking docs

    let body = reqwest::blocking::get("https://www.rust-lang.org")?
        .text()?;
    
    println!("body = {:?}", body);
    

    Note that when you try to use this one, you will still get that

    cannot use the ? operator in a function that returns ()

    and you will need to set a return type on main like

    fn main() -> Result<(), reqwest::Error> {
    

    See Why do try!() and ? not compile when used in a function that doesn't return Option or Result? for more info.