DEV Community

BC
BC

Posted on

Day14:Call Web API - 100DayOfRust

In this example, we will call a bitcoin web api with reqwest crate to get the json format data, then use serde_json crate to parse json to get price.

First, we add those 2 dependencies:

[dependencies]
reqwest = "0.9.22"
serde_json = "1.0.42"
Enter fullscreen mode Exit fullscreen mode

Then in main.rs:

use serde_json::{Value};
use reqwest;

fn main() {
    let url = "https://blockchain.info/ticker";
    println!("Send request to: {}", url);
    // 1st way, use .json()
    let val: Value = reqwest::get(url).unwrap().json().unwrap();
    println!("Bitcoin price: ${}", val["USD"]["last"]);

    // 2nd way, use .text() then serde_json::from_str
    let text = reqwest::get(url).unwrap().text().unwrap();
    let val2: Value = serde_json::from_str(&text).unwrap();
    println!("Bitcoin price: ${}", val2["USD"]["last"]);
}

Enter fullscreen mode Exit fullscreen mode

Run it with cargo run:

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

Top comments (0)