cs2-api 1.0.0

CS2 API client for Rust: Counter-Strike 2 live scores, match results, player stats, teams, rankings (world + VRS), events and skin prices
Documentation
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! # cs2-api: Counter-Strike 2 esports and skin market API client for Rust
//!
//! The official Rust client for the **CS2 API** at [cs2-api.org](https://cs2-api.org).
//!
//! Live scores, match results, schedules, player stats (rating, ADR, KAST), teams and rosters,
//! the world ranking and Valve Regional Standings, events and brackets, transfers, and skin
//! prices across marketplaces.
//!
//! Get a free API key (500 requests/month): <https://cs2-api.org>
//!
//! ## Quickstart
//!
//! ```no_run
//! use cs2_api::Client;
//!
//! fn main() -> Result<(), cs2_api::Error> {
//!     // Reads the key from the CITO_API_KEY environment variable.
//!     let cs2 = Client::from_env()?;
//!
//!     // Every match being played right now.
//!     let live = cs2.live()?;
//!     for m in live.as_array().into_iter().flatten() {
//!         println!(
//!             "{} {}-{} {}",
//!             m["team1Name"], m["team1Score"], m["team2Score"], m["team2Name"]
//!         );
//!     }
//!
//!     let ranking = cs2.world_ranking(10)?;
//!     let vitality = cs2.team("vitality")?; // roster + recent results
//!     let donk = cs2.player("donk")?;
//!     let prices = cs2.skin_prices("ak-47-redline-field-tested-1ab1a2dc")?;
//!     println!("{ranking}\n{vitality}\n{donk}\n{prices}");
//!     Ok(())
//! }
//! ```
//!
//! Every method returns the `data` field of the API's JSON envelope as a
//! [`serde_json::Value`]. Use [`Client::get_raw`] to get the whole envelope, including `meta`
//! for pagination.

use std::fmt;
use std::io::Read;
use std::time::Duration;

pub use serde_json::Value;

/// Crate version, sent in the `User-Agent` header.
pub const VERSION: &str = "1.0.0";

/// Default API base URL.
pub const DEFAULT_BASE_URL: &str = "https://api.citoapi.com/api/v1";

/// Environment variable the client reads the API key from.
pub const API_KEY_ENV: &str = "CITO_API_KEY";

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(20);

/// Errors returned by the client.
#[derive(Debug)]
pub enum Error {
    /// The API answered with an error status, or with `success: false`.
    Http {
        /// HTTP status code (200 when the envelope said `success: false`).
        status: u16,
        /// The API's machine-readable error code, when present.
        code: Option<String>,
        /// The API's error message.
        message: String,
    },
    /// The request never got an HTTP response (DNS, connection, TLS, timeout).
    Transport(String),
    /// The response body was not valid JSON.
    Decode(String),
    /// No API key was passed and `CITO_API_KEY` is not set.
    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 {}

/// Percent-encodes one URL path segment (or query component).
///
/// Everything except RFC 3986 unreserved characters (`A-Z a-z 0-9 - _ . ~`) is encoded,
/// so `/`, `?`, `#` and spaces can never change the request path.
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
}

/// Builds a full request URL from a base URL, a path and query pairs.
///
/// Pairs with an empty value are dropped, like `None` values in the other clients.
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)
}

/// Builder for a [`Client`] with a custom base URL or timeout.
#[derive(Debug, Clone, Default)]
pub struct ClientBuilder {
    api_key: Option<String>,
    base_url: Option<String>,
    timeout: Option<Duration>,
}

impl ClientBuilder {
    /// Sets the API key. When not set, `CITO_API_KEY` is read.
    pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    /// Sets the base URL (default `https://api.citoapi.com/api/v1`).
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Sets the request timeout (default 20 seconds).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Builds the client. Fails with [`Error::MissingKey`] when no key is available.
    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,
        })
    }
}

/// CS2 API client. Cheap to clone; clones share one connection pool.
#[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 {
    /// Creates a client with an explicit API key.
    pub fn new(api_key: impl Into<String>) -> Result<Self, Error> {
        ClientBuilder::default().api_key(api_key).build()
    }

    /// Creates a client with the key from the `CITO_API_KEY` environment variable.
    pub fn from_env() -> Result<Self, Error> {
        ClientBuilder::default().build()
    }

    /// Starts a [`ClientBuilder`] to set the base URL or timeout.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// The base URL requests go to.
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// The request timeout.
    pub fn timeout(&self) -> Duration {
        self.timeout
    }

    /// Any endpoint. Returns the whole response envelope (`success`, `data`, `meta`).
    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)
    }

    /// Any endpoint. Returns `data`.
    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())])
    }

    // ---- Live ----

    /// Every match being played now, with series score, current map and map score.
    pub fn live(&self) -> Result<Value, Error> {
        self.get("/cs2/live", &[])
    }

    /// Round-level scoreboard for one live match: sides, round, player K/D/ADR, money.
    pub fn live_scoreboard(&self, match_id: &str) -> Result<Value, Error> {
        self.get(
            &format!("/cs2/live/{}/scoreboard", encode_segment(match_id)),
            &[],
        )
    }

    // ---- Matches ----

    /// Upcoming matches (the other clients default `limit` to 50).
    pub fn upcoming(&self, limit: u32) -> Result<Value, Error> {
        self.get_limit("/cs2/matches/upcoming", limit)
    }

    /// Recent match results (the other clients default `limit` to 50).
    pub fn results(&self, limit: u32) -> Result<Value, Error> {
        self.get_limit("/cs2/matches/results", limit)
    }

    /// Today's matches.
    pub fn today(&self) -> Result<Value, Error> {
        self.get("/cs2/matches/today", &[])
    }

    /// One match by id.
    pub fn match_by_id(&self, match_id: &str) -> Result<Value, Error> {
        self.get(&format!("/cs2/matches/{}", encode_segment(match_id)), &[])
    }

    /// Alias of [`Client::match_by_id`].
    pub fn match_(&self, match_id: &str) -> Result<Value, Error> {
        self.match_by_id(match_id)
    }

    /// Per-map results for a match.
    pub fn match_maps(&self, match_id: &str) -> Result<Value, Error> {
        self.get(
            &format!("/cs2/matches/{}/maps", encode_segment(match_id)),
            &[],
        )
    }

    /// Player stats for a match.
    pub fn match_player_stats(&self, match_id: &str) -> Result<Value, Error> {
        self.get(
            &format!("/cs2/matches/{}/player-stats", encode_segment(match_id)),
            &[],
        )
    }

    /// Streams for a match.
    pub fn match_streams(&self, match_id: &str) -> Result<Value, Error> {
        self.get(
            &format!("/cs2/matches/{}/streams", encode_segment(match_id)),
            &[],
        )
    }

    // ---- Teams ----

    /// Team with roster and recent results. Accepts an id or a slug such as "vitality".
    pub fn team(&self, team: &str) -> Result<Value, Error> {
        self.get(&format!("/cs2/teams/{}", encode_segment(team)), &[])
    }

    /// A team's matches (the other clients default `limit` to 20).
    pub fn team_matches(&self, team: &str, limit: u32) -> Result<Value, Error> {
        self.get_limit(
            &format!("/cs2/teams/{}/matches", encode_segment(team)),
            limit,
        )
    }

    /// A team's aggregate stats.
    pub fn team_stats(&self, team: &str) -> Result<Value, Error> {
        self.get(&format!("/cs2/teams/{}/stats", encode_segment(team)), &[])
    }

    /// A team's per-map stats.
    pub fn team_map_stats(&self, team: &str) -> Result<Value, Error> {
        self.get(
            &format!("/cs2/teams/{}/map-stats", encode_segment(team)),
            &[],
        )
    }

    /// Head-to-head record between two teams.
    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)
            ),
            &[],
        )
    }

    // ---- Players ----

    /// Player profile. Accepts an id or a slug such as "donk".
    pub fn player(&self, player: &str) -> Result<Value, Error> {
        self.get(&format!("/cs2/players/{}", encode_segment(player)), &[])
    }

    /// Search players by name (the other clients default `limit` to 10).
    pub fn search_players(&self, query: &str, limit: u32) -> Result<Value, Error> {
        self.get(
            "/cs2/players/search",
            &[("q", query), ("limit", &limit.to_string())],
        )
    }

    /// A player's stats.
    pub fn player_stats(&self, player: &str) -> Result<Value, Error> {
        self.get(
            &format!("/cs2/players/{}/stats", encode_segment(player)),
            &[],
        )
    }

    /// A player's matches (the other clients default `limit` to 20).
    pub fn player_matches(&self, player: &str, limit: u32) -> Result<Value, Error> {
        self.get_limit(
            &format!("/cs2/players/{}/matches", encode_segment(player)),
            limit,
        )
    }

    // ---- Events ----

    /// status: "upcoming", "live" or "recent" (anything else means "upcoming").
    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)
    }

    /// One event by id or slug.
    pub fn event(&self, event: &str) -> Result<Value, Error> {
        self.get(&format!("/cs2/events/{}", encode_segment(event)), &[])
    }

    /// An event's matches.
    pub fn event_matches(&self, event: &str) -> Result<Value, Error> {
        self.get(
            &format!("/cs2/events/{}/matches", encode_segment(event)),
            &[],
        )
    }

    /// An event's standings.
    pub fn event_standings(&self, event: &str) -> Result<Value, Error> {
        self.get(
            &format!("/cs2/events/{}/standings", encode_segment(event)),
            &[],
        )
    }

    /// An event's bracket.
    pub fn event_bracket(&self, event: &str) -> Result<Value, Error> {
        self.get(
            &format!("/cs2/events/{}/bracket", encode_segment(event)),
            &[],
        )
    }

    // ---- Rankings and stats ----

    /// World ranking (the other clients default `limit` to 30).
    pub fn world_ranking(&self, limit: u32) -> Result<Value, Error> {
        self.get_limit("/cs2/rankings/world", limit)
    }

    /// Valve Regional Standings.
    pub fn vrs_ranking(&self, limit: u32) -> Result<Value, Error> {
        self.get_limit("/cs2/rankings/vrs", limit)
    }

    /// metric: e.g. "rating", "adr", "kast", "kd", "kills", "opening-kills".
    pub fn leaderboard(&self, metric: &str, limit: u32) -> Result<Value, Error> {
        self.get_limit(
            &format!("/cs2/leaderboards/{}", encode_segment(metric)),
            limit,
        )
    }

    /// Recent roster transfers (the other clients default `limit` to 50).
    pub fn transfers(&self, limit: u32) -> Result<Value, Error> {
        self.get_limit("/cs2/transfers/recent", limit)
    }

    /// Teams, players, events and matches matching a name.
    pub fn search(&self, query: &str) -> Result<Value, Error> {
        self.get("/cs2/search", &[("q", query)])
    }

    // ---- Skins ----

    /// Search one word at a time ("redline"), or pass filters such as
    /// `[("weapon", "AK-47"), ("skin_name", "Redline")]` for an exact skin.
    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", &params)
    }

    /// One skin by slug.
    pub fn skin(&self, slug: &str) -> Result<Value, Error> {
        self.get(&format!("/cs2/skins/{}", encode_segment(slug)), &[])
    }

    /// The skin's price on every marketplace, with listing counts and buy links.
    pub fn skin_prices(&self, slug: &str) -> Result<Value, Error> {
        self.get(&format!("/cs2/skins/{}/prices", encode_segment(slug)), &[])
    }

    /// A skin's price history, optionally limited to a range such as "30d".
    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(""))],
        )
    }

    /// Biggest movers: `{"gainers": [...], "losers": [...]}`.
    /// The other clients default to timeframe "7d" and limit 20.
    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),
            ],
        )
    }
}