1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use reqwest;
use serde_json;
use serde_json::{Value};
use std::fmt;
pub struct CoinGeckoAPI {
version: String,
base_url: String,
}
impl Default for CoinGeckoAPI {
fn default () -> CoinGeckoAPI {
CoinGeckoAPI {
version: String::from("v3"),
base_url: String::from("https://api.coingecko.com"),
}
}
}
impl CoinGeckoAPI {
pub fn build_base_url(&self) -> String {
format!("{}/api/{}", self.base_url, self.version)
}
pub fn to_json(response_text: &String) -> Value {
let v: Value = serde_json::from_str(response_text).unwrap();
v
}
pub async fn get_json<T: Route>(&self, resource: &T) -> Result<Value, Box<dyn std::error::Error>> {
let resp = self.get(resource).await?;
if resp == "" || resp == "{}" {
return Ok(Value::Null)
}
let json = CoinGeckoAPI::to_json(&resp);
Ok(json)
}
pub async fn get<T: Route>(&self, resource: &T) -> Result<String, Box<dyn std::error::Error>> {
let base_url = self.build_base_url();
let api_endpoint = resource.route();
let url = format!("{}{}", base_url, api_endpoint);
let client = reqwest::Client::new();
let resp: String = client.get(url).header("accept", "application/json")
.send()
.await?.text().await?;
println!("from get --- {:?}", resp);
Ok(resp)
}
}
pub trait Route {
fn query_string(&self) -> String;
fn api_endpoint(&self) -> String;
fn route(&self) -> String {
format!("{}{}", self.api_endpoint(), self.query_string())
}
fn format_query<T: fmt::Display + Copy + std::cmp::PartialEq>(&self, name: String, value: T, default: T) -> String {
if value != default {
return format!("{}={}", name, value)
}
"".to_string()
}
fn collect_query_params(&self, query_params: Vec<String>) -> String {
let mut query = String::from("?");
let collected: String = query_params.into_iter()
.filter(|x| **x != String::from(""))
.collect::<Vec<String>>()
.join("&");
query.push_str(&collected);
query
}
}
pub mod simple;
pub mod coins;
pub mod contract;
pub mod asset_platforms;
pub mod categories;
pub mod exchanges;
pub mod finance;
pub mod indexes;
pub mod derivatives;
pub mod status_updates;
pub mod events;
pub mod exchange_rates;
pub mod trending;
pub mod global;
pub mod companies;