What would the blocking version of this usage of reqwest be?

I'm new to Rust and am also trying to learn to make API calls with reqwest. I was wondering if someone would be kind enough to show me what the blocking version of the below code would look like?

extern crate reqwest;
extern crate tokio;

use serde::{Serialize, Deserialize};
use serde_json;

#[derive(Deserialize, Serialize, Debug)]
struct CatFact {
    text: String
}

#[tokio::main]
async fn main() ->  Result<(), Box<dyn std::error::Error>> {
    let url = "https://cat-fact.herokuapp.com/facts";
    let res = reqwest::get(url).await?;
    let json = res.text().await.unwrap();
    let facts: Vec<CatFact> = serde_json::from_str(&json).unwrap();

    println!("facts = {:#?}", facts);

    Ok(())
}

Also, why is it necessary to call the await method on res.text() in this case? What exactly is going on there?

Note: I have moved your question to a new topic.

It would look like this:

use serde::{Deserialize, Serialize};
use serde_json;

#[derive(Deserialize, Serialize, Debug)]
struct CatFact {
    text: String,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://cat-fact.herokuapp.com/facts";
    let res = reqwest::blocking::get(url)?;
    let json = res.text().unwrap();
    let facts: Vec<CatFact> = serde_json::from_str(&json).unwrap();

    println!("facts = {:#?}", facts);

    Ok(())
}

Note that you need to enable the blocking feature of reqwest to do this.

[dependencies]
reqwest = { version = "0.11", features = ["blocking"] }

The get method returns as soon as the web server has responded with the headers of the response, but before the entire body has been sent. This would allow you to e.g. write the response to a file as it arrives without first reading the entire body into memory first.

The .text() call says "wait until we have the entire response in memory, then give it to me as a String".

1 Like

Also, note that by enabling the json feature of reqwest those two lines :

let json = res.text().unwrap();
let facts: Vec<CatFact> = serde_json::from_str(&json).unwrap();

can become :

let facts: Vec<CatFact> = res.json()?;
1 Like

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.