Skip to main content

cs2_api/
lib.rs

1//! # cs2-api: Counter-Strike 2 esports and skin market API client for Rust
2//!
3//! The official Rust client for the **CS2 API** at [cs2-api.org](https://cs2-api.org).
4//!
5//! Live scores, match results, schedules, player stats (rating, ADR, KAST), teams and rosters,
6//! the world ranking and Valve Regional Standings, events and brackets, transfers, and skin
7//! prices across marketplaces.
8//!
9//! Get a free API key (500 requests/month): <https://cs2-api.org>
10//!
11//! ## Quickstart
12//!
13//! ```no_run
14//! use cs2_api::Client;
15//!
16//! fn main() -> Result<(), cs2_api::Error> {
17//!     // Reads the key from the CITO_API_KEY environment variable.
18//!     let cs2 = Client::from_env()?;
19//!
20//!     // Every match being played right now.
21//!     let live = cs2.live()?;
22//!     for m in live.as_array().into_iter().flatten() {
23//!         println!(
24//!             "{} {}-{} {}",
25//!             m["team1Name"], m["team1Score"], m["team2Score"], m["team2Name"]
26//!         );
27//!     }
28//!
29//!     let ranking = cs2.world_ranking(10)?;
30//!     let vitality = cs2.team("vitality")?; // roster + recent results
31//!     let donk = cs2.player("donk")?;
32//!     let prices = cs2.skin_prices("ak-47-redline-field-tested-1ab1a2dc")?;
33//!     println!("{ranking}\n{vitality}\n{donk}\n{prices}");
34//!     Ok(())
35//! }
36//! ```
37//!
38//! Every method returns the `data` field of the API's JSON envelope as a
39//! [`serde_json::Value`]. Use [`Client::get_raw`] to get the whole envelope, including `meta`
40//! for pagination.
41
42use std::fmt;
43use std::io::Read;
44use std::time::Duration;
45
46pub use serde_json::Value;
47
48/// Crate version, sent in the `User-Agent` header.
49pub const VERSION: &str = "1.0.0";
50
51/// Default API base URL.
52pub const DEFAULT_BASE_URL: &str = "https://api.citoapi.com/api/v1";
53
54/// Environment variable the client reads the API key from.
55pub const API_KEY_ENV: &str = "CITO_API_KEY";
56
57const DEFAULT_TIMEOUT: Duration = Duration::from_secs(20);
58
59/// Errors returned by the client.
60#[derive(Debug)]
61pub enum Error {
62    /// The API answered with an error status, or with `success: false`.
63    Http {
64        /// HTTP status code (200 when the envelope said `success: false`).
65        status: u16,
66        /// The API's machine-readable error code, when present.
67        code: Option<String>,
68        /// The API's error message.
69        message: String,
70    },
71    /// The request never got an HTTP response (DNS, connection, TLS, timeout).
72    Transport(String),
73    /// The response body was not valid JSON.
74    Decode(String),
75    /// No API key was passed and `CITO_API_KEY` is not set.
76    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
102/// Percent-encodes one URL path segment (or query component).
103///
104/// Everything except RFC 3986 unreserved characters (`A-Z a-z 0-9 - _ . ~`) is encoded,
105/// so `/`, `?`, `#` and spaces can never change the request path.
106pub 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
119/// Builds a full request URL from a base URL, a path and query pairs.
120///
121/// Pairs with an empty value are dropped, like `None` values in the other clients.
122pub 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/// Builder for a [`Client`] with a custom base URL or timeout.
165#[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    /// Sets the API key. When not set, `CITO_API_KEY` is read.
174    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    /// Sets the base URL (default `https://api.citoapi.com/api/v1`).
180    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    /// Sets the request timeout (default 20 seconds).
186    pub fn timeout(mut self, timeout: Duration) -> Self {
187        self.timeout = Some(timeout);
188        self
189    }
190
191    /// Builds the client. Fails with [`Error::MissingKey`] when no key is available.
192    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/// CS2 API client. Cheap to clone; clones share one connection pool.
219#[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    /// Creates a client with an explicit API key.
239    pub fn new(api_key: impl Into<String>) -> Result<Self, Error> {
240        ClientBuilder::default().api_key(api_key).build()
241    }
242
243    /// Creates a client with the key from the `CITO_API_KEY` environment variable.
244    pub fn from_env() -> Result<Self, Error> {
245        ClientBuilder::default().build()
246    }
247
248    /// Starts a [`ClientBuilder`] to set the base URL or timeout.
249    pub fn builder() -> ClientBuilder {
250        ClientBuilder::default()
251    }
252
253    /// The base URL requests go to.
254    pub fn base_url(&self) -> &str {
255        &self.base_url
256    }
257
258    /// The request timeout.
259    pub fn timeout(&self) -> Duration {
260        self.timeout
261    }
262
263    /// Any endpoint. Returns the whole response envelope (`success`, `data`, `meta`).
264    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    /// Any endpoint. Returns `data`.
301    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    // ---- Live ----
313
314    /// Every match being played now, with series score, current map and map score.
315    pub fn live(&self) -> Result<Value, Error> {
316        self.get("/cs2/live", &[])
317    }
318
319    /// Round-level scoreboard for one live match: sides, round, player K/D/ADR, money.
320    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    // ---- Matches ----
328
329    /// Upcoming matches (the other clients default `limit` to 50).
330    pub fn upcoming(&self, limit: u32) -> Result<Value, Error> {
331        self.get_limit("/cs2/matches/upcoming", limit)
332    }
333
334    /// Recent match results (the other clients default `limit` to 50).
335    pub fn results(&self, limit: u32) -> Result<Value, Error> {
336        self.get_limit("/cs2/matches/results", limit)
337    }
338
339    /// Today's matches.
340    pub fn today(&self) -> Result<Value, Error> {
341        self.get("/cs2/matches/today", &[])
342    }
343
344    /// One match by id.
345    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    /// Alias of [`Client::match_by_id`].
350    pub fn match_(&self, match_id: &str) -> Result<Value, Error> {
351        self.match_by_id(match_id)
352    }
353
354    /// Per-map results for a match.
355    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    /// Player stats for a match.
363    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    /// Streams for a match.
371    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    // ---- Teams ----
379
380    /// Team with roster and recent results. Accepts an id or a slug such as "vitality".
381    pub fn team(&self, team: &str) -> Result<Value, Error> {
382        self.get(&format!("/cs2/teams/{}", encode_segment(team)), &[])
383    }
384
385    /// A team's matches (the other clients default `limit` to 20).
386    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    /// A team's aggregate stats.
394    pub fn team_stats(&self, team: &str) -> Result<Value, Error> {
395        self.get(&format!("/cs2/teams/{}/stats", encode_segment(team)), &[])
396    }
397
398    /// A team's per-map stats.
399    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    /// Head-to-head record between two teams.
407    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    // ---- Players ----
419
420    /// Player profile. Accepts an id or a slug such as "donk".
421    pub fn player(&self, player: &str) -> Result<Value, Error> {
422        self.get(&format!("/cs2/players/{}", encode_segment(player)), &[])
423    }
424
425    /// Search players by name (the other clients default `limit` to 10).
426    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    /// A player's stats.
434    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    /// A player's matches (the other clients default `limit` to 20).
442    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    // ---- Events ----
450
451    /// status: "upcoming", "live" or "recent" (anything else means "upcoming").
452    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    /// One event by id or slug.
462    pub fn event(&self, event: &str) -> Result<Value, Error> {
463        self.get(&format!("/cs2/events/{}", encode_segment(event)), &[])
464    }
465
466    /// An event's matches.
467    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    /// An event's standings.
475    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    /// An event's bracket.
483    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    // ---- Rankings and stats ----
491
492    /// World ranking (the other clients default `limit` to 30).
493    pub fn world_ranking(&self, limit: u32) -> Result<Value, Error> {
494        self.get_limit("/cs2/rankings/world", limit)
495    }
496
497    /// Valve Regional Standings.
498    pub fn vrs_ranking(&self, limit: u32) -> Result<Value, Error> {
499        self.get_limit("/cs2/rankings/vrs", limit)
500    }
501
502    /// metric: e.g. "rating", "adr", "kast", "kd", "kills", "opening-kills".
503    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    /// Recent roster transfers (the other clients default `limit` to 50).
511    pub fn transfers(&self, limit: u32) -> Result<Value, Error> {
512        self.get_limit("/cs2/transfers/recent", limit)
513    }
514
515    /// Teams, players, events and matches matching a name.
516    pub fn search(&self, query: &str) -> Result<Value, Error> {
517        self.get("/cs2/search", &[("q", query)])
518    }
519
520    // ---- Skins ----
521
522    /// Search one word at a time ("redline"), or pass filters such as
523    /// `[("weapon", "AK-47"), ("skin_name", "Redline")]` for an exact skin.
524    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", &params)
535    }
536
537    /// One skin by slug.
538    pub fn skin(&self, slug: &str) -> Result<Value, Error> {
539        self.get(&format!("/cs2/skins/{}", encode_segment(slug)), &[])
540    }
541
542    /// The skin's price on every marketplace, with listing counts and buy links.
543    pub fn skin_prices(&self, slug: &str) -> Result<Value, Error> {
544        self.get(&format!("/cs2/skins/{}/prices", encode_segment(slug)), &[])
545    }
546
547    /// A skin's price history, optionally limited to a range such as "30d".
548    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    /// Biggest movers: `{"gainers": [...], "losers": [...]}`.
556    /// The other clients default to timeframe "7d" and limit 20.
557    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}