DEV Community

loading...

Day27:surf: async HTTP client - 100DayOfRust

0xbf profile image Bo ・1 min read

In previous post I wrote on how to call web API with the reqwest crate, we can do the same thing with surf.

In Cargo.toml:

[dependencies]
async-std = "1.4.0"
surf = "1.0.3"
serde_json = "1.0.42"
Enter fullscreen mode Exit fullscreen mode

In main.rs:

use async_std::task;
use serde_json::{Value};
use surf; 


fn main() {
    let url = "https://blockchain.info/ticker";
    println!("Send request to: {}", url);

    task::block_on(async {
        // first way, auto parse returned string as json
        let val:Value = surf::get(url).recv_json().await.unwrap();
        println!("Bitcoin Price: ${}", val["USD"]["last"]);

        // second way, use returned string
        let valstr = surf::get(url).recv_string().await.unwrap();
        let val:Value = serde_json::from_str(&valstr).unwrap();
        println!("Bitcoin Price: ${}", val["USD"]["last"]);
    }); 
}
Enter fullscreen mode Exit fullscreen mode

Run code cargo run:

Send request to: https://blockchain.info/ticker
Bitcoin Price: $7346.23
Bitcoin Price: $7346.23
Enter fullscreen mode Exit fullscreen mode

Reference:

  1. https://docs.rs/surf/1.0.3/surf/
  2. https://github.com/http-rs/surf

Discussion (0)

Forem Open with the Forem app