jsonrustjson-deserializationserdereqwest

json method not found when Deserializing a request response


I'm pretty new to Rust, and I just cannot seem to find the solution to this problem. I am trying to get the response of the get request as json.

#[macro_use]
extern crate serde;
extern crate serde_derive;
extern crate reqwest;
use reqwest::Error;

fn main(){
    #[derive(Deserialize)]

struct Ip {
    origin: String,
}

let json: Ip = reqwest::get("http://httpbin.org/ip").json();
//reqwest::get("http://httpbin.org/ip")?.json()?;
}

Here is cargo.toml

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_derive = "1.0"
reqwest = { version = "0.10", features = ["blocking"] }

The error I keep getting is json error

Also, if i use

reqwest::get("http://httpbin.org/ip")?.json()?;

(Adding the question marks) I get another error saying

cannot use the `?` operator in a function that returns `()`
this function should return `Result` or `Option` to accept `?`

How do i fix these?


Solution

  • Per the doc, you need to enable the json reqwest feature in your Cargo.toml:

    reqwest = { version = "0.10", features = ["blocking", "json"] }
    

    Also, reqwest::get is part of the async API. Since your main is synchronous, you want reqwest::blocking::get