Pythonで書くとこんな感じ
import requests
def get_bitcoin_price():
url = 'https://coincheck.com/api/ticker'
response = requests.get(url)
data = response.json()
last_price = data['last']
return last_price
bitcoin_price = get_bitcoin_price()
print(f"現在のbtc価格: {bitcoin_price} JPY")
これをRustで書く。構造体にしてあげる。
use reqwest::Client;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Clone, Debug)]
struct Price {
last: f32,
bid: f32,
ask: f32,
high: f32,
volume: f32,
timestamp: u32
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = "https://coincheck.com/api/ticker";
let contents = reqwest::get(url).await?.text().await?;
println!("{:?}", &contents);
let res: Price = serde_json::from_str(&contents).unwrap();
println!("{:?}", res.last);
Ok(())
}
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.05s
Running `target/debug/wallet`
“{\”last\”:14905296.0,\”bid\”:14904987.0,\”ask\”:14907006.0,\”high\”:15136729.0,\”low\”:14578786.0,\”volume\”:1207.84604682,\”timestamp\”:1736567711}”
14905296.0
coincheckは日本円なので、USD変換のAPIの方が良いな。かつ、Ethの値も一緒に取れると尚良
use reqwest::Client;
use serde::{Serialize, Deserialize};
use serde_json::{Value};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = "https://api.coinbase.com/v2/exchange-rates?currency=BTC";
let contents = reqwest::get(url).await?.text().await?;
// println!("{:?}", &contents);
let res: Value = serde_json::from_str(&contents).unwrap();
println!("{:?}", res["data"]["rates"]["USD"]);
Ok(())
}
coinbaseのapiだと、btcもethもusdベースで取得できる。よっしゃああああああああああああ