use std::fmt;
use std::io::Read;
use std::time::Duration;
pub use serde_json::Value;
pub const VERSION: &str = "1.0.0";
pub const DEFAULT_BASE_URL: &str = "https://api.citoapi.com/api/v1";
pub const API_KEY_ENV: &str = "CITO_API_KEY";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(20);
#[derive(Debug)]
pub enum Error {
Http {
status: u16,
code: Option<String>,
message: String,
},
Transport(String),
Decode(String),
MissingKey,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Http {
status,
code: Some(code),
message,
} => write!(f, "CS2 API error {status} ({code}): {message}"),
Error::Http {
status, message, ..
} => write!(f, "CS2 API error {status}: {message}"),
Error::Transport(msg) => write!(f, "CS2 API transport error: {msg}"),
Error::Decode(msg) => write!(f, "CS2 API response was not valid JSON: {msg}"),
Error::MissingKey => write!(
f,
"Missing API key. Get a free key at https://cs2-api.org and set CITO_API_KEY (or pass it to Client::new)."
),
}
}
}
impl std::error::Error for Error {}
pub fn encode_segment(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for b in value.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
pub fn build_url(base_url: &str, path: &str, query: &[(&str, &str)]) -> String {
let mut url = base_url.trim_end_matches('/').to_string();
if !path.starts_with('/') {
url.push('/');
}
url.push_str(path);
let mut first = true;
for (key, value) in query {
if value.is_empty() {
continue;
}
url.push(if first { '?' } else { '&' });
first = false;
url.push_str(&encode_segment(key));
url.push('=');
url.push_str(&encode_segment(value));
}
url
}
fn envelope_error(body: &Value) -> (Option<String>, Option<String>) {
let err = body.get("error");
let code = err
.and_then(|e| e.get("code"))
.and_then(Value::as_str)
.map(str::to_string);
let message = err
.and_then(|e| e.get("message"))
.and_then(Value::as_str)
.map(str::to_string);
(code, message)
}
fn read_body(response: ureq::Response) -> Result<Vec<u8>, Error> {
let mut buf = Vec::new();
response
.into_reader()
.read_to_end(&mut buf)
.map_err(|e| Error::Transport(e.to_string()))?;
Ok(buf)
}
#[derive(Debug, Clone, Default)]
pub struct ClientBuilder {
api_key: Option<String>,
base_url: Option<String>,
timeout: Option<Duration>,
}
impl ClientBuilder {
pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
self.api_key = Some(api_key.into());
self
}
pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = Some(base_url.into());
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn build(self) -> Result<Client, Error> {
let api_key = match self.api_key {
Some(key) => key,
None => std::env::var(API_KEY_ENV).unwrap_or_default(),
};
if api_key.trim().is_empty() {
return Err(Error::MissingKey);
}
let timeout = self.timeout.unwrap_or(DEFAULT_TIMEOUT);
let agent = ureq::AgentBuilder::new()
.timeout(timeout)
.user_agent(&format!("cs2-api-rust/{VERSION}"))
.build();
Ok(Client {
api_key,
base_url: self
.base_url
.unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
.trim_end_matches('/')
.to_string(),
timeout,
agent,
})
}
}
#[derive(Clone)]
pub struct Client {
api_key: String,
base_url: String,
timeout: Duration,
agent: ureq::Agent,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client")
.field("base_url", &self.base_url)
.field("timeout", &self.timeout)
.field("api_key", &"<redacted>")
.finish()
}
}
impl Client {
pub fn new(api_key: impl Into<String>) -> Result<Self, Error> {
ClientBuilder::default().api_key(api_key).build()
}
pub fn from_env() -> Result<Self, Error> {
ClientBuilder::default().build()
}
pub fn builder() -> ClientBuilder {
ClientBuilder::default()
}
pub fn base_url(&self) -> &str {
&self.base_url
}
pub fn timeout(&self) -> Duration {
self.timeout
}
pub fn get_raw(&self, path: &str, query: &[(&str, &str)]) -> Result<Value, Error> {
let url = build_url(&self.base_url, path, query);
let result = self
.agent
.get(&url)
.set("x-api-key", &self.api_key)
.set("accept", "application/json")
.call();
let body = match result {
Ok(response) => read_body(response)?,
Err(ureq::Error::Status(status, response)) => {
let bytes = read_body(response).unwrap_or_default();
let parsed: Option<Value> = serde_json::from_slice(&bytes).ok();
let (code, message) = parsed.as_ref().map(envelope_error).unwrap_or_default();
return Err(Error::Http {
status,
code,
message: message
.unwrap_or_else(|| format!("Request failed with status {status}")),
});
}
Err(ureq::Error::Transport(t)) => return Err(Error::Transport(t.to_string())),
};
let value: Value =
serde_json::from_slice(&body).map_err(|e| Error::Decode(e.to_string()))?;
if value.get("success") == Some(&Value::Bool(false)) {
let (code, message) = envelope_error(&value);
return Err(Error::Http {
status: 200,
code,
message: message.unwrap_or_else(|| "Request failed".to_string()),
});
}
Ok(value)
}
pub fn get(&self, path: &str, query: &[(&str, &str)]) -> Result<Value, Error> {
match self.get_raw(path, query)? {
Value::Object(mut map) => Ok(map.remove("data").unwrap_or(Value::Null)),
other => Ok(other),
}
}
fn get_limit(&self, path: &str, limit: u32) -> Result<Value, Error> {
self.get(path, &[("limit", &limit.to_string())])
}
pub fn live(&self) -> Result<Value, Error> {
self.get("/cs2/live", &[])
}
pub fn live_scoreboard(&self, match_id: &str) -> Result<Value, Error> {
self.get(
&format!("/cs2/live/{}/scoreboard", encode_segment(match_id)),
&[],
)
}
pub fn upcoming(&self, limit: u32) -> Result<Value, Error> {
self.get_limit("/cs2/matches/upcoming", limit)
}
pub fn results(&self, limit: u32) -> Result<Value, Error> {
self.get_limit("/cs2/matches/results", limit)
}
pub fn today(&self) -> Result<Value, Error> {
self.get("/cs2/matches/today", &[])
}
pub fn match_by_id(&self, match_id: &str) -> Result<Value, Error> {
self.get(&format!("/cs2/matches/{}", encode_segment(match_id)), &[])
}
pub fn match_(&self, match_id: &str) -> Result<Value, Error> {
self.match_by_id(match_id)
}
pub fn match_maps(&self, match_id: &str) -> Result<Value, Error> {
self.get(
&format!("/cs2/matches/{}/maps", encode_segment(match_id)),
&[],
)
}
pub fn match_player_stats(&self, match_id: &str) -> Result<Value, Error> {
self.get(
&format!("/cs2/matches/{}/player-stats", encode_segment(match_id)),
&[],
)
}
pub fn match_streams(&self, match_id: &str) -> Result<Value, Error> {
self.get(
&format!("/cs2/matches/{}/streams", encode_segment(match_id)),
&[],
)
}
pub fn team(&self, team: &str) -> Result<Value, Error> {
self.get(&format!("/cs2/teams/{}", encode_segment(team)), &[])
}
pub fn team_matches(&self, team: &str, limit: u32) -> Result<Value, Error> {
self.get_limit(
&format!("/cs2/teams/{}/matches", encode_segment(team)),
limit,
)
}
pub fn team_stats(&self, team: &str) -> Result<Value, Error> {
self.get(&format!("/cs2/teams/{}/stats", encode_segment(team)), &[])
}
pub fn team_map_stats(&self, team: &str) -> Result<Value, Error> {
self.get(
&format!("/cs2/teams/{}/map-stats", encode_segment(team)),
&[],
)
}
pub fn head_to_head(&self, team_a: &str, team_b: &str) -> Result<Value, Error> {
self.get(
&format!(
"/cs2/teams/{}/h2h/{}",
encode_segment(team_a),
encode_segment(team_b)
),
&[],
)
}
pub fn player(&self, player: &str) -> Result<Value, Error> {
self.get(&format!("/cs2/players/{}", encode_segment(player)), &[])
}
pub fn search_players(&self, query: &str, limit: u32) -> Result<Value, Error> {
self.get(
"/cs2/players/search",
&[("q", query), ("limit", &limit.to_string())],
)
}
pub fn player_stats(&self, player: &str) -> Result<Value, Error> {
self.get(
&format!("/cs2/players/{}/stats", encode_segment(player)),
&[],
)
}
pub fn player_matches(&self, player: &str, limit: u32) -> Result<Value, Error> {
self.get_limit(
&format!("/cs2/players/{}/matches", encode_segment(player)),
limit,
)
}
pub fn events(&self, status: &str, limit: u32) -> Result<Value, Error> {
let path = match status {
"live" => "/cs2/events/live",
"recent" => "/cs2/events/recent",
_ => "/cs2/events/upcoming",
};
self.get_limit(path, limit)
}
pub fn event(&self, event: &str) -> Result<Value, Error> {
self.get(&format!("/cs2/events/{}", encode_segment(event)), &[])
}
pub fn event_matches(&self, event: &str) -> Result<Value, Error> {
self.get(
&format!("/cs2/events/{}/matches", encode_segment(event)),
&[],
)
}
pub fn event_standings(&self, event: &str) -> Result<Value, Error> {
self.get(
&format!("/cs2/events/{}/standings", encode_segment(event)),
&[],
)
}
pub fn event_bracket(&self, event: &str) -> Result<Value, Error> {
self.get(
&format!("/cs2/events/{}/bracket", encode_segment(event)),
&[],
)
}
pub fn world_ranking(&self, limit: u32) -> Result<Value, Error> {
self.get_limit("/cs2/rankings/world", limit)
}
pub fn vrs_ranking(&self, limit: u32) -> Result<Value, Error> {
self.get_limit("/cs2/rankings/vrs", limit)
}
pub fn leaderboard(&self, metric: &str, limit: u32) -> Result<Value, Error> {
self.get_limit(
&format!("/cs2/leaderboards/{}", encode_segment(metric)),
limit,
)
}
pub fn transfers(&self, limit: u32) -> Result<Value, Error> {
self.get_limit("/cs2/transfers/recent", limit)
}
pub fn search(&self, query: &str) -> Result<Value, Error> {
self.get("/cs2/search", &[("q", query)])
}
pub fn search_skins(
&self,
query: Option<&str>,
filters: &[(&str, &str)],
) -> Result<Value, Error> {
let mut params: Vec<(&str, &str)> = Vec::with_capacity(filters.len() + 1);
if let Some(q) = query {
params.push(("q", q));
}
params.extend_from_slice(filters);
self.get("/cs2/skins/search", ¶ms)
}
pub fn skin(&self, slug: &str) -> Result<Value, Error> {
self.get(&format!("/cs2/skins/{}", encode_segment(slug)), &[])
}
pub fn skin_prices(&self, slug: &str) -> Result<Value, Error> {
self.get(&format!("/cs2/skins/{}/prices", encode_segment(slug)), &[])
}
pub fn skin_history(&self, slug: &str, range: Option<&str>) -> Result<Value, Error> {
self.get(
&format!("/cs2/skins/{}/history", encode_segment(slug)),
&[("range", range.unwrap_or(""))],
)
}
pub fn trending_skins(
&self,
timeframe: &str,
limit: u32,
min_price: Option<f64>,
) -> Result<Value, Error> {
let limit = limit.to_string();
let min_price = min_price.map(|p| p.to_string()).unwrap_or_default();
self.get(
"/cs2/skins/trending",
&[
("timeframe", timeframe),
("limit", &limit),
("minPrice", &min_price),
],
)
}
}