1use std::fmt;
43use std::io::Read;
44use std::time::Duration;
45
46pub use serde_json::Value;
47
48pub const VERSION: &str = "1.0.0";
50
51pub const DEFAULT_BASE_URL: &str = "https://api.citoapi.com/api/v1";
53
54pub const API_KEY_ENV: &str = "CITO_API_KEY";
56
57const DEFAULT_TIMEOUT: Duration = Duration::from_secs(20);
58
59#[derive(Debug)]
61pub enum Error {
62 Http {
64 status: u16,
66 code: Option<String>,
68 message: String,
70 },
71 Transport(String),
73 Decode(String),
75 MissingKey,
77}
78
79impl fmt::Display for Error {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 match self {
82 Error::Http {
83 status,
84 code: Some(code),
85 message,
86 } => write!(f, "CS2 API error {status} ({code}): {message}"),
87 Error::Http {
88 status, message, ..
89 } => write!(f, "CS2 API error {status}: {message}"),
90 Error::Transport(msg) => write!(f, "CS2 API transport error: {msg}"),
91 Error::Decode(msg) => write!(f, "CS2 API response was not valid JSON: {msg}"),
92 Error::MissingKey => write!(
93 f,
94 "Missing API key. Get a free key at https://cs2-api.org and set CITO_API_KEY (or pass it to Client::new)."
95 ),
96 }
97 }
98}
99
100impl std::error::Error for Error {}
101
102pub fn encode_segment(value: &str) -> String {
107 let mut out = String::with_capacity(value.len());
108 for b in value.bytes() {
109 match b {
110 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
111 out.push(b as char)
112 }
113 _ => out.push_str(&format!("%{b:02X}")),
114 }
115 }
116 out
117}
118
119pub fn build_url(base_url: &str, path: &str, query: &[(&str, &str)]) -> String {
123 let mut url = base_url.trim_end_matches('/').to_string();
124 if !path.starts_with('/') {
125 url.push('/');
126 }
127 url.push_str(path);
128 let mut first = true;
129 for (key, value) in query {
130 if value.is_empty() {
131 continue;
132 }
133 url.push(if first { '?' } else { '&' });
134 first = false;
135 url.push_str(&encode_segment(key));
136 url.push('=');
137 url.push_str(&encode_segment(value));
138 }
139 url
140}
141
142fn envelope_error(body: &Value) -> (Option<String>, Option<String>) {
143 let err = body.get("error");
144 let code = err
145 .and_then(|e| e.get("code"))
146 .and_then(Value::as_str)
147 .map(str::to_string);
148 let message = err
149 .and_then(|e| e.get("message"))
150 .and_then(Value::as_str)
151 .map(str::to_string);
152 (code, message)
153}
154
155fn read_body(response: ureq::Response) -> Result<Vec<u8>, Error> {
156 let mut buf = Vec::new();
157 response
158 .into_reader()
159 .read_to_end(&mut buf)
160 .map_err(|e| Error::Transport(e.to_string()))?;
161 Ok(buf)
162}
163
164#[derive(Debug, Clone, Default)]
166pub struct ClientBuilder {
167 api_key: Option<String>,
168 base_url: Option<String>,
169 timeout: Option<Duration>,
170}
171
172impl ClientBuilder {
173 pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
175 self.api_key = Some(api_key.into());
176 self
177 }
178
179 pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
181 self.base_url = Some(base_url.into());
182 self
183 }
184
185 pub fn timeout(mut self, timeout: Duration) -> Self {
187 self.timeout = Some(timeout);
188 self
189 }
190
191 pub fn build(self) -> Result<Client, Error> {
193 let api_key = match self.api_key {
194 Some(key) => key,
195 None => std::env::var(API_KEY_ENV).unwrap_or_default(),
196 };
197 if api_key.trim().is_empty() {
198 return Err(Error::MissingKey);
199 }
200 let timeout = self.timeout.unwrap_or(DEFAULT_TIMEOUT);
201 let agent = ureq::AgentBuilder::new()
202 .timeout(timeout)
203 .user_agent(&format!("cs2-api-rust/{VERSION}"))
204 .build();
205 Ok(Client {
206 api_key,
207 base_url: self
208 .base_url
209 .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
210 .trim_end_matches('/')
211 .to_string(),
212 timeout,
213 agent,
214 })
215 }
216}
217
218#[derive(Clone)]
220pub struct Client {
221 api_key: String,
222 base_url: String,
223 timeout: Duration,
224 agent: ureq::Agent,
225}
226
227impl fmt::Debug for Client {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 f.debug_struct("Client")
230 .field("base_url", &self.base_url)
231 .field("timeout", &self.timeout)
232 .field("api_key", &"<redacted>")
233 .finish()
234 }
235}
236
237impl Client {
238 pub fn new(api_key: impl Into<String>) -> Result<Self, Error> {
240 ClientBuilder::default().api_key(api_key).build()
241 }
242
243 pub fn from_env() -> Result<Self, Error> {
245 ClientBuilder::default().build()
246 }
247
248 pub fn builder() -> ClientBuilder {
250 ClientBuilder::default()
251 }
252
253 pub fn base_url(&self) -> &str {
255 &self.base_url
256 }
257
258 pub fn timeout(&self) -> Duration {
260 self.timeout
261 }
262
263 pub fn get_raw(&self, path: &str, query: &[(&str, &str)]) -> Result<Value, Error> {
265 let url = build_url(&self.base_url, path, query);
266 let result = self
267 .agent
268 .get(&url)
269 .set("x-api-key", &self.api_key)
270 .set("accept", "application/json")
271 .call();
272 let body = match result {
273 Ok(response) => read_body(response)?,
274 Err(ureq::Error::Status(status, response)) => {
275 let bytes = read_body(response).unwrap_or_default();
276 let parsed: Option<Value> = serde_json::from_slice(&bytes).ok();
277 let (code, message) = parsed.as_ref().map(envelope_error).unwrap_or_default();
278 return Err(Error::Http {
279 status,
280 code,
281 message: message
282 .unwrap_or_else(|| format!("Request failed with status {status}")),
283 });
284 }
285 Err(ureq::Error::Transport(t)) => return Err(Error::Transport(t.to_string())),
286 };
287 let value: Value =
288 serde_json::from_slice(&body).map_err(|e| Error::Decode(e.to_string()))?;
289 if value.get("success") == Some(&Value::Bool(false)) {
290 let (code, message) = envelope_error(&value);
291 return Err(Error::Http {
292 status: 200,
293 code,
294 message: message.unwrap_or_else(|| "Request failed".to_string()),
295 });
296 }
297 Ok(value)
298 }
299
300 pub fn get(&self, path: &str, query: &[(&str, &str)]) -> Result<Value, Error> {
302 match self.get_raw(path, query)? {
303 Value::Object(mut map) => Ok(map.remove("data").unwrap_or(Value::Null)),
304 other => Ok(other),
305 }
306 }
307
308 fn get_limit(&self, path: &str, limit: u32) -> Result<Value, Error> {
309 self.get(path, &[("limit", &limit.to_string())])
310 }
311
312 pub fn live(&self) -> Result<Value, Error> {
316 self.get("/cs2/live", &[])
317 }
318
319 pub fn live_scoreboard(&self, match_id: &str) -> Result<Value, Error> {
321 self.get(
322 &format!("/cs2/live/{}/scoreboard", encode_segment(match_id)),
323 &[],
324 )
325 }
326
327 pub fn upcoming(&self, limit: u32) -> Result<Value, Error> {
331 self.get_limit("/cs2/matches/upcoming", limit)
332 }
333
334 pub fn results(&self, limit: u32) -> Result<Value, Error> {
336 self.get_limit("/cs2/matches/results", limit)
337 }
338
339 pub fn today(&self) -> Result<Value, Error> {
341 self.get("/cs2/matches/today", &[])
342 }
343
344 pub fn match_by_id(&self, match_id: &str) -> Result<Value, Error> {
346 self.get(&format!("/cs2/matches/{}", encode_segment(match_id)), &[])
347 }
348
349 pub fn match_(&self, match_id: &str) -> Result<Value, Error> {
351 self.match_by_id(match_id)
352 }
353
354 pub fn match_maps(&self, match_id: &str) -> Result<Value, Error> {
356 self.get(
357 &format!("/cs2/matches/{}/maps", encode_segment(match_id)),
358 &[],
359 )
360 }
361
362 pub fn match_player_stats(&self, match_id: &str) -> Result<Value, Error> {
364 self.get(
365 &format!("/cs2/matches/{}/player-stats", encode_segment(match_id)),
366 &[],
367 )
368 }
369
370 pub fn match_streams(&self, match_id: &str) -> Result<Value, Error> {
372 self.get(
373 &format!("/cs2/matches/{}/streams", encode_segment(match_id)),
374 &[],
375 )
376 }
377
378 pub fn team(&self, team: &str) -> Result<Value, Error> {
382 self.get(&format!("/cs2/teams/{}", encode_segment(team)), &[])
383 }
384
385 pub fn team_matches(&self, team: &str, limit: u32) -> Result<Value, Error> {
387 self.get_limit(
388 &format!("/cs2/teams/{}/matches", encode_segment(team)),
389 limit,
390 )
391 }
392
393 pub fn team_stats(&self, team: &str) -> Result<Value, Error> {
395 self.get(&format!("/cs2/teams/{}/stats", encode_segment(team)), &[])
396 }
397
398 pub fn team_map_stats(&self, team: &str) -> Result<Value, Error> {
400 self.get(
401 &format!("/cs2/teams/{}/map-stats", encode_segment(team)),
402 &[],
403 )
404 }
405
406 pub fn head_to_head(&self, team_a: &str, team_b: &str) -> Result<Value, Error> {
408 self.get(
409 &format!(
410 "/cs2/teams/{}/h2h/{}",
411 encode_segment(team_a),
412 encode_segment(team_b)
413 ),
414 &[],
415 )
416 }
417
418 pub fn player(&self, player: &str) -> Result<Value, Error> {
422 self.get(&format!("/cs2/players/{}", encode_segment(player)), &[])
423 }
424
425 pub fn search_players(&self, query: &str, limit: u32) -> Result<Value, Error> {
427 self.get(
428 "/cs2/players/search",
429 &[("q", query), ("limit", &limit.to_string())],
430 )
431 }
432
433 pub fn player_stats(&self, player: &str) -> Result<Value, Error> {
435 self.get(
436 &format!("/cs2/players/{}/stats", encode_segment(player)),
437 &[],
438 )
439 }
440
441 pub fn player_matches(&self, player: &str, limit: u32) -> Result<Value, Error> {
443 self.get_limit(
444 &format!("/cs2/players/{}/matches", encode_segment(player)),
445 limit,
446 )
447 }
448
449 pub fn events(&self, status: &str, limit: u32) -> Result<Value, Error> {
453 let path = match status {
454 "live" => "/cs2/events/live",
455 "recent" => "/cs2/events/recent",
456 _ => "/cs2/events/upcoming",
457 };
458 self.get_limit(path, limit)
459 }
460
461 pub fn event(&self, event: &str) -> Result<Value, Error> {
463 self.get(&format!("/cs2/events/{}", encode_segment(event)), &[])
464 }
465
466 pub fn event_matches(&self, event: &str) -> Result<Value, Error> {
468 self.get(
469 &format!("/cs2/events/{}/matches", encode_segment(event)),
470 &[],
471 )
472 }
473
474 pub fn event_standings(&self, event: &str) -> Result<Value, Error> {
476 self.get(
477 &format!("/cs2/events/{}/standings", encode_segment(event)),
478 &[],
479 )
480 }
481
482 pub fn event_bracket(&self, event: &str) -> Result<Value, Error> {
484 self.get(
485 &format!("/cs2/events/{}/bracket", encode_segment(event)),
486 &[],
487 )
488 }
489
490 pub fn world_ranking(&self, limit: u32) -> Result<Value, Error> {
494 self.get_limit("/cs2/rankings/world", limit)
495 }
496
497 pub fn vrs_ranking(&self, limit: u32) -> Result<Value, Error> {
499 self.get_limit("/cs2/rankings/vrs", limit)
500 }
501
502 pub fn leaderboard(&self, metric: &str, limit: u32) -> Result<Value, Error> {
504 self.get_limit(
505 &format!("/cs2/leaderboards/{}", encode_segment(metric)),
506 limit,
507 )
508 }
509
510 pub fn transfers(&self, limit: u32) -> Result<Value, Error> {
512 self.get_limit("/cs2/transfers/recent", limit)
513 }
514
515 pub fn search(&self, query: &str) -> Result<Value, Error> {
517 self.get("/cs2/search", &[("q", query)])
518 }
519
520 pub fn search_skins(
525 &self,
526 query: Option<&str>,
527 filters: &[(&str, &str)],
528 ) -> Result<Value, Error> {
529 let mut params: Vec<(&str, &str)> = Vec::with_capacity(filters.len() + 1);
530 if let Some(q) = query {
531 params.push(("q", q));
532 }
533 params.extend_from_slice(filters);
534 self.get("/cs2/skins/search", ¶ms)
535 }
536
537 pub fn skin(&self, slug: &str) -> Result<Value, Error> {
539 self.get(&format!("/cs2/skins/{}", encode_segment(slug)), &[])
540 }
541
542 pub fn skin_prices(&self, slug: &str) -> Result<Value, Error> {
544 self.get(&format!("/cs2/skins/{}/prices", encode_segment(slug)), &[])
545 }
546
547 pub fn skin_history(&self, slug: &str, range: Option<&str>) -> Result<Value, Error> {
549 self.get(
550 &format!("/cs2/skins/{}/history", encode_segment(slug)),
551 &[("range", range.unwrap_or(""))],
552 )
553 }
554
555 pub fn trending_skins(
558 &self,
559 timeframe: &str,
560 limit: u32,
561 min_price: Option<f64>,
562 ) -> Result<Value, Error> {
563 let limit = limit.to_string();
564 let min_price = min_price.map(|p| p.to_string()).unwrap_or_default();
565 self.get(
566 "/cs2/skins/trending",
567 &[
568 ("timeframe", timeframe),
569 ("limit", &limit),
570 ("minPrice", &min_price),
571 ],
572 )
573 }
574}