Search code examples
rustreqwest

Dynamically receive json data in rust with reqwest


Ive been trying to receive json data with reqwest and serde but I keep getting the error:

Error: reqwest::Error { kind: Decode, source: Error("expected value", line: 1, column: 1) }

This is my code so far:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url: String = String::from("https://api.slothpixel.me/api/players/leastrio");
    let echo_json: serde_json::Value = reqwest::Client::new()
        .get(url)
        .send()
        .await?
        .json()
        .await?;
    
    println!("{:#?}", echo_json);
    Ok(())
}
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
serde_json = "1"

Solution

  • So I've trie a few things, and it seems you need to add a user agent for it to work. No idea why the documentation doesn't mention it. And I guess reqwest doesn't provied one by default.

    reqwest::Client::new()
            .get(url)
            .header("User-Agent", "Reqwest Rust Test")
            .send()
            .await?
            .json()
            .await?;
    

    I used this and it worked!