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"
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"]);
});
}
Run code cargo run
:
Send request to: https://blockchain.info/ticker
Bitcoin Price: $7346.23
Bitcoin Price: $7346.23
Top comments (0)