rustreqwest

How to get body of response with reqwest?


I'm trying to send a GET request to the Binance API. But I'm getting this output in my terminal instead of the data:

Response { url: Url { scheme: "https", cannot_be_a_base: false, username: "", password: None, host: Some(Domain("api.binance.com")), port: None, path: "/api/v3/exchangeInfo", query: Some("symbol=BNBBTC"), fragment: None }, status: 200, headers: {"content-type": "application/json;charset=UTF-8", "content-length": "1515", "connection": "keep-alive", "date": "Thu, 23 Dec 2021 23:28:24 GMT", "server": "nginx", "vary": "Accept-Encoding", "x-mbx-uuid": "1244d760-2c41-46df-910f-b95c4a312bc2", "x-mbx-used-weight": "10", "x-mbx-used-weight-1m": "10", "strict-transport-security": "max-age=31536000; includeSubdomains", "x-frame-options": "SAMEORIGIN", "x-xss-protection": "1; mode=block", "x-content-type-options": "nosniff", "content-security-policy": "default-src 'self'", "x-content-security-policy": "default-src 'self'", "x-webkit-csp": "default-src 'self'", "cache-control": "no-cache, no-store, must-revalidate", "pragma": "no-cache", "expires": "0", "access-control-allow-origin": "*", "access-control-allow-methods": "GET, HEAD, OPTIONS", "x-cache": "Miss from cloudfront", "via": "1.1 08b9c2fd11813ffdb8fa03129d0a465d.cloudfront.net (CloudFront)", "x-amz-cf-pop": "FRA56-C2", "x-amz-cf-id": "EBp6UQUM3B2Lz0iAoPM88INjL4C0ugIgxmaoTPzi0Q4WPxfG46p8Yw=="} }

My code looks like this:

async fn main() {
    let client = Client::new();
    let res = client.get("https://api.binance.com/api/v3/exchangeInfo?symbol=BNBBTC")
    // .header(USER_AGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36")
    // .header(CONTENT_TYPE, "application/json")
    // .header(CACHE_CONTROL, "no-store")
    // .header(PRAGMA, "no-cache")
    .send().await;
    println!("{:?}", res.unwrap());
}

What am I doing wrong?


Solution

  • The Response that you're printing is basically just the initial HTTP info (e.g. status and headers). You'll need to wait for the payload as well using methods depending on what you're expecting:

    In this case it looks like you're getting a JSON payload so using .json() into a deserializable type sounds like the right way to go, but if your only goal is to print it then .text() is probably the simpler approach.

    async fn main() {
        let client = Client::new();
        let res = client
            .get("https://api.binance.com/api/v3/exchangeInfo?symbol=BNBBTC")
            .send()
            .await
            .expect("failed to get response")
            .text()
            .await
            .expect("failed to get payload");
    
        println!("{}", res);
    }
    

    Related: