valorant-esports-api 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cito API
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.4
2
+ Name: valorant-esports-api
3
+ Version: 1.0.0
4
+ Summary: Official Valorant esports API client for live VCT scores, WebSocket rooms, historical matches, per-map player stats, rankings, teams, events, and sample CSVs. Standard library only.
5
+ Author: Cito API
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://valorant-api.org/
8
+ Project-URL: Documentation, https://citoapi.com/docs/api/valorant/live/
9
+ Project-URL: Source, https://github.com/Cito-GG/valorant-esports-api
10
+ Project-URL: Issues, https://github.com/Cito-GG/valorant-esports-api/issues
11
+ Project-URL: Get a free API key, https://citoapi.com/signup?game=valorant&utm_source=npm-pypi&utm_medium=referral&utm_campaign=valorant-esports-api
12
+ Keywords: valorant,valorant-api,valorant-esports,vct,live-valorant-api,historical-valorant-api,websocket,esports
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Games/Entertainment
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.8
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Dynamic: license-file
23
+
24
+ # valorant-esports-api (Python)
25
+
26
+ [![PyPI](https://img.shields.io/pypi/v/valorant-esports-api)](https://pypi.org/project/valorant-esports-api/) [![license](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
27
+
28
+ Official Python client for the **Valorant esports API** at [valorant-api.org](https://valorant-api.org/) and [citoapi.com/valorant/](https://citoapi.com/valorant/). Zero runtime dependencies (Python 3.8+ standard library only).
29
+
30
+ Use one client as both a **live Valorant API** and a **historical Valorant API** across `71,596` matches, `6,081` teams, `43,029` players, and `3,099` events (VCT 2021-2026, Challengers, and Ascension):
31
+
32
+ - Live match scores, schedules, results, and match detail (`veto`, `streams`, `games`)
33
+ - Per-map game telemetry: round timelines, economy conversions, ACS, K/D/A, ADR, KAST, HS%, and FK/FD
34
+ - Teams, active rosters, coaching staff, and regional rankings
35
+ - Player profiles (`career_summary` and `agents` stats) and match logs
36
+ - Events/tournaments and roster transfers
37
+ - **VCT WebSocket** URL and `"rooms"` subscription payload builders (`wss://api.citoapi.com/api/v1/valorant/live/ws`)
38
+ - Public sample CSV downloads (`matches.csv` and `players.csv`, no API key required)
39
+
40
+ > **Get a free API key** (500 requests/month, no card): **[Sign up for Valorant API](https://citoapi.com/signup?game=valorant&utm_source=npm-pypi&utm_medium=referral&utm_campaign=valorant-esports-api)**
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install valorant-esports-api
46
+ ```
47
+
48
+ ## Quickstart
49
+
50
+ ```python
51
+ import json
52
+ from valorant_esports_api import ValorantApi
53
+
54
+ api = ValorantApi() # reads CITO_API_KEY from environment
55
+
56
+ # 1. Live Valorant matches
57
+ live = api.live()
58
+ for m in live["matches"]:
59
+ t = m["teams"]
60
+ s = m["score"]
61
+ print(f"{t['team1_name']} {s['team1']}-{s['team2']} {t['team2_name']} ({m['event_name']})")
62
+
63
+ # 2. Historical Valorant matches with filters
64
+ history = api.matches(
65
+ status="Completed",
66
+ date_from="2026-01-01",
67
+ date_to="2026-03-01",
68
+ limit=25,
69
+ )
70
+ first_match = history["matches"][0]
71
+ games = api.match_games(first_match["id"])
72
+
73
+ # 3. Player career summary and per-agent stats
74
+ player = api.player("tenz")
75
+ print(player["career_summary"])
76
+ print(player["agents"][:3])
77
+
78
+ # 4. Regional team rankings and transfers
79
+ emea_rankings = api.rankings(region="europe", limit=10)
80
+ recent_transfers = api.transfers(limit=20)
81
+ ```
82
+
83
+ ## Public Sample CSVs (No API Key Required)
84
+
85
+ ```python
86
+ matches_csv = api.sample_matches_csv()
87
+ players_csv = api.sample_players_csv()
88
+ print(matches_csv.splitlines()[:5])
89
+ ```
90
+
91
+ Direct URLs:
92
+
93
+ - `https://api.citoapi.com/api/v1/exports/sample/valorant/matches.csv`
94
+ - `https://api.citoapi.com/api/v1/exports/sample/valorant/players.csv`
95
+
96
+ ## Live VCT WebSocket Helper
97
+
98
+ The **VCT WebSocket** endpoint is `wss://api.citoapi.com/api/v1/valorant/live/ws` (available on Pro + `$15/mo` Live WebSockets add-on, Scale, and Business CSV). Authenticate via the `X-API-Key` header for servers/bots, or `?api_key=<key>` for browser sources.
99
+
100
+ ```python
101
+ import json
102
+
103
+ ws_url = api.ws_url() # or api.ws_url("your_key") for ?api_key=... query auth
104
+ subscribe_msg = api.ws_subscribe_payload(["all"]) # {"action": "subscribe", "rooms": ["all"]}
105
+ match_msg = api.ws_subscribe_payload(["match:val-match-12345"])
106
+
107
+ print(ws_url)
108
+ print(json.dumps(subscribe_msg))
109
+ print(json.dumps(match_msg))
110
+ ```
111
+
112
+ Note: Subscribe messages use the `"rooms"` key (`{"action": "subscribe", "rooms": ["all"]}`). Metering is `0` requests per pushed event, `1` request on upgrade + `1` request per `15s` open.
113
+
114
+ ## Methods
115
+
116
+ All methods return the unwrapped `data` object by default; pass `raw=True` to `api.get(path, params, raw=True)` for the full `{success, data, meta}` envelope.
117
+
118
+ | Area | Methods |
119
+ |---|---|
120
+ | Overview | `overview()` |
121
+ | Matches | `live(...)`, `upcoming(...)`, `results(...)`, `matches(status=..., event_id=..., team_id=..., date_from=..., date_to=..., limit=..., offset=...)`, `match(match_id)`, `match_games(match_id)` |
122
+ | Teams | `teams(...)`, `team(team_id)`, `team_matches(team_id, ...)` |
123
+ | Players | `players(...)`, `player(player_id)`, `player_matches(player_id, ...)` |
124
+ | Events | `events(...)`, `event(event_id)`, `event_matches(event_id, ...)` |
125
+ | Rankings & Transfers | `rankings(region=..., date=..., limit=...)`, `transfers(...)` |
126
+ | Sample CSVs | `sample_matches_csv()`, `sample_players_csv()` |
127
+ | WebSocket | `ws_url(api_key=None)`, `ws_subscribe_payload(rooms=None)` |
128
+ | Escape hatch | `get(path, params=None, raw=False)` |
129
+
130
+ Errors raise `ValorantApiError` with `.status`, `.code`, and `.body`.
131
+
132
+ ## Pricing & Tiers
133
+
134
+ - **Free** (`$0/mo`, `500` reqs/mo) & **Starter** (`$15/mo`, `10,000` reqs/mo): REST with `60s` live delay, full historical access.
135
+ - **Pro** (`$59/mo`, `250,000` reqs/mo): `0s` live REST + optional `+$15/mo` Live WebSockets add-on (unlocks `/live/ws` and `/live/stream`).
136
+ - **Scale** (`$100/mo`, `1,000,000` reqs/mo): `0s` live REST + WebSocket & SSE included.
137
+ - **Business CSV** (`$299/mo`, `3,000,000` reqs/mo): `0s` live REST + WebSocket & SSE included + full historical CSV exports.
138
+
139
+ ## Links
140
+
141
+ - Live Valorant API Docs: https://citoapi.com/docs/api/valorant/live/
142
+ - Live WebSocket Docs: https://citoapi.com/docs/api/valorant/live/websocket/
143
+ - Historical Valorant API Docs: https://citoapi.com/docs/api/valorant/historical/
144
+ - Historical CSV Dataset: https://valorant-api.org/historical-csv-dataset/
145
+ - Pricing: https://citoapi.com/pricing/
146
+ - GitHub Monorepo: https://github.com/Cito-GG/valorant-esports-api
147
+
148
+ MIT licensed.
@@ -0,0 +1,125 @@
1
+ # valorant-esports-api (Python)
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/valorant-esports-api)](https://pypi.org/project/valorant-esports-api/) [![license](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
4
+
5
+ Official Python client for the **Valorant esports API** at [valorant-api.org](https://valorant-api.org/) and [citoapi.com/valorant/](https://citoapi.com/valorant/). Zero runtime dependencies (Python 3.8+ standard library only).
6
+
7
+ Use one client as both a **live Valorant API** and a **historical Valorant API** across `71,596` matches, `6,081` teams, `43,029` players, and `3,099` events (VCT 2021-2026, Challengers, and Ascension):
8
+
9
+ - Live match scores, schedules, results, and match detail (`veto`, `streams`, `games`)
10
+ - Per-map game telemetry: round timelines, economy conversions, ACS, K/D/A, ADR, KAST, HS%, and FK/FD
11
+ - Teams, active rosters, coaching staff, and regional rankings
12
+ - Player profiles (`career_summary` and `agents` stats) and match logs
13
+ - Events/tournaments and roster transfers
14
+ - **VCT WebSocket** URL and `"rooms"` subscription payload builders (`wss://api.citoapi.com/api/v1/valorant/live/ws`)
15
+ - Public sample CSV downloads (`matches.csv` and `players.csv`, no API key required)
16
+
17
+ > **Get a free API key** (500 requests/month, no card): **[Sign up for Valorant API](https://citoapi.com/signup?game=valorant&utm_source=npm-pypi&utm_medium=referral&utm_campaign=valorant-esports-api)**
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install valorant-esports-api
23
+ ```
24
+
25
+ ## Quickstart
26
+
27
+ ```python
28
+ import json
29
+ from valorant_esports_api import ValorantApi
30
+
31
+ api = ValorantApi() # reads CITO_API_KEY from environment
32
+
33
+ # 1. Live Valorant matches
34
+ live = api.live()
35
+ for m in live["matches"]:
36
+ t = m["teams"]
37
+ s = m["score"]
38
+ print(f"{t['team1_name']} {s['team1']}-{s['team2']} {t['team2_name']} ({m['event_name']})")
39
+
40
+ # 2. Historical Valorant matches with filters
41
+ history = api.matches(
42
+ status="Completed",
43
+ date_from="2026-01-01",
44
+ date_to="2026-03-01",
45
+ limit=25,
46
+ )
47
+ first_match = history["matches"][0]
48
+ games = api.match_games(first_match["id"])
49
+
50
+ # 3. Player career summary and per-agent stats
51
+ player = api.player("tenz")
52
+ print(player["career_summary"])
53
+ print(player["agents"][:3])
54
+
55
+ # 4. Regional team rankings and transfers
56
+ emea_rankings = api.rankings(region="europe", limit=10)
57
+ recent_transfers = api.transfers(limit=20)
58
+ ```
59
+
60
+ ## Public Sample CSVs (No API Key Required)
61
+
62
+ ```python
63
+ matches_csv = api.sample_matches_csv()
64
+ players_csv = api.sample_players_csv()
65
+ print(matches_csv.splitlines()[:5])
66
+ ```
67
+
68
+ Direct URLs:
69
+
70
+ - `https://api.citoapi.com/api/v1/exports/sample/valorant/matches.csv`
71
+ - `https://api.citoapi.com/api/v1/exports/sample/valorant/players.csv`
72
+
73
+ ## Live VCT WebSocket Helper
74
+
75
+ The **VCT WebSocket** endpoint is `wss://api.citoapi.com/api/v1/valorant/live/ws` (available on Pro + `$15/mo` Live WebSockets add-on, Scale, and Business CSV). Authenticate via the `X-API-Key` header for servers/bots, or `?api_key=<key>` for browser sources.
76
+
77
+ ```python
78
+ import json
79
+
80
+ ws_url = api.ws_url() # or api.ws_url("your_key") for ?api_key=... query auth
81
+ subscribe_msg = api.ws_subscribe_payload(["all"]) # {"action": "subscribe", "rooms": ["all"]}
82
+ match_msg = api.ws_subscribe_payload(["match:val-match-12345"])
83
+
84
+ print(ws_url)
85
+ print(json.dumps(subscribe_msg))
86
+ print(json.dumps(match_msg))
87
+ ```
88
+
89
+ Note: Subscribe messages use the `"rooms"` key (`{"action": "subscribe", "rooms": ["all"]}`). Metering is `0` requests per pushed event, `1` request on upgrade + `1` request per `15s` open.
90
+
91
+ ## Methods
92
+
93
+ All methods return the unwrapped `data` object by default; pass `raw=True` to `api.get(path, params, raw=True)` for the full `{success, data, meta}` envelope.
94
+
95
+ | Area | Methods |
96
+ |---|---|
97
+ | Overview | `overview()` |
98
+ | Matches | `live(...)`, `upcoming(...)`, `results(...)`, `matches(status=..., event_id=..., team_id=..., date_from=..., date_to=..., limit=..., offset=...)`, `match(match_id)`, `match_games(match_id)` |
99
+ | Teams | `teams(...)`, `team(team_id)`, `team_matches(team_id, ...)` |
100
+ | Players | `players(...)`, `player(player_id)`, `player_matches(player_id, ...)` |
101
+ | Events | `events(...)`, `event(event_id)`, `event_matches(event_id, ...)` |
102
+ | Rankings & Transfers | `rankings(region=..., date=..., limit=...)`, `transfers(...)` |
103
+ | Sample CSVs | `sample_matches_csv()`, `sample_players_csv()` |
104
+ | WebSocket | `ws_url(api_key=None)`, `ws_subscribe_payload(rooms=None)` |
105
+ | Escape hatch | `get(path, params=None, raw=False)` |
106
+
107
+ Errors raise `ValorantApiError` with `.status`, `.code`, and `.body`.
108
+
109
+ ## Pricing & Tiers
110
+
111
+ - **Free** (`$0/mo`, `500` reqs/mo) & **Starter** (`$15/mo`, `10,000` reqs/mo): REST with `60s` live delay, full historical access.
112
+ - **Pro** (`$59/mo`, `250,000` reqs/mo): `0s` live REST + optional `+$15/mo` Live WebSockets add-on (unlocks `/live/ws` and `/live/stream`).
113
+ - **Scale** (`$100/mo`, `1,000,000` reqs/mo): `0s` live REST + WebSocket & SSE included.
114
+ - **Business CSV** (`$299/mo`, `3,000,000` reqs/mo): `0s` live REST + WebSocket & SSE included + full historical CSV exports.
115
+
116
+ ## Links
117
+
118
+ - Live Valorant API Docs: https://citoapi.com/docs/api/valorant/live/
119
+ - Live WebSocket Docs: https://citoapi.com/docs/api/valorant/live/websocket/
120
+ - Historical Valorant API Docs: https://citoapi.com/docs/api/valorant/historical/
121
+ - Historical CSV Dataset: https://valorant-api.org/historical-csv-dataset/
122
+ - Pricing: https://citoapi.com/pricing/
123
+ - GitHub Monorepo: https://github.com/Cito-GG/valorant-esports-api
124
+
125
+ MIT licensed.
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "valorant-esports-api"
7
+ version = "1.0.0"
8
+ description = "Official Valorant esports API client for live VCT scores, WebSocket rooms, historical matches, per-map player stats, rankings, teams, events, and sample CSVs. Standard library only."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Cito API" }]
14
+ keywords = [
15
+ "valorant",
16
+ "valorant-api",
17
+ "valorant-esports",
18
+ "vct",
19
+ "live-valorant-api",
20
+ "historical-valorant-api",
21
+ "websocket",
22
+ "esports",
23
+ ]
24
+ classifiers = [
25
+ "Programming Language :: Python :: 3",
26
+ "Operating System :: OS Independent",
27
+ "Intended Audience :: Developers",
28
+ "Topic :: Games/Entertainment",
29
+ "Topic :: Software Development :: Libraries :: Python Modules",
30
+ "Typing :: Typed",
31
+ ]
32
+
33
+ [project.urls]
34
+ Homepage = "https://valorant-api.org/"
35
+ Documentation = "https://citoapi.com/docs/api/valorant/live/"
36
+ Source = "https://github.com/Cito-GG/valorant-esports-api"
37
+ Issues = "https://github.com/Cito-GG/valorant-esports-api/issues"
38
+ "Get a free API key" = "https://citoapi.com/signup?game=valorant&utm_source=npm-pypi&utm_medium=referral&utm_campaign=valorant-esports-api"
39
+
40
+ [tool.setuptools.packages.find]
41
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,444 @@
1
+ """valorant-esports-api: Official Valorant esports API client (Python 3.8+, standard library only).
2
+
3
+ Live VCT scores, WebSocket rooms, historical matches (2021-2026), per-map round timelines
4
+ and player stats, regional team rankings, team rosters, player career summaries and agent
5
+ stats, events, transfers, and public sample CSVs.
6
+
7
+ Get a free API key (500 requests/month): https://valorant-api.org/
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+ from typing import Any, Dict, Optional, Sequence
18
+
19
+ __version__ = "1.0.0"
20
+ __all__ = [
21
+ "ValorantApi",
22
+ "ValorantApiError",
23
+ "DEFAULT_BASE_URL",
24
+ "DEFAULT_WS_URL",
25
+ "SAMPLE_MATCHES_CSV_URL",
26
+ "SAMPLE_PLAYERS_CSV_URL",
27
+ ]
28
+
29
+ DEFAULT_BASE_URL = "https://api.citoapi.com/api/v1/valorant"
30
+ DEFAULT_WS_URL = "wss://api.citoapi.com/api/v1/valorant/live/ws"
31
+ SAMPLE_MATCHES_CSV_URL = "https://api.citoapi.com/api/v1/exports/sample/valorant/matches.csv"
32
+ SAMPLE_PLAYERS_CSV_URL = "https://api.citoapi.com/api/v1/exports/sample/valorant/players.csv"
33
+ SIGNUP_URL = (
34
+ "https://citoapi.com/signup?game=valorant&utm_source=npm-pypi"
35
+ "&utm_medium=referral&utm_campaign=valorant-esports-api"
36
+ )
37
+
38
+
39
+ class ValorantApiError(Exception):
40
+ """Raised when the Valorant API returns an error status, invalid payload, or missing key."""
41
+
42
+ def __init__(self, message: str, status: int = 0, body: Any = None):
43
+ super().__init__(message)
44
+ self.status = status
45
+ self.body = body
46
+ self.code = ((body or {}).get("error") or {}).get("code") if isinstance(body, dict) else None
47
+
48
+
49
+ def _q(value: str) -> str:
50
+ return urllib.parse.quote(str(value), safe="")
51
+
52
+
53
+ def _clean_params(params: Optional[Dict[str, Any]]) -> Dict[str, str]:
54
+ out: Dict[str, str] = {}
55
+ for k, v in (params or {}).items():
56
+ if v is None or v == "":
57
+ continue
58
+ if isinstance(v, bool):
59
+ out[k] = "true" if v else "false"
60
+ else:
61
+ out[k] = str(v)
62
+ return out
63
+
64
+
65
+ class ValorantApi:
66
+ """Zero-dependency client for the Cito Valorant Esports API."""
67
+
68
+ def __init__(
69
+ self,
70
+ api_key: Optional[str] = None,
71
+ base_url: str = DEFAULT_BASE_URL,
72
+ timeout: float = 20,
73
+ ):
74
+ self.api_key = api_key if api_key is not None else os.environ.get("CITO_API_KEY")
75
+ self.base_url = base_url.rstrip("/")
76
+ self.timeout = timeout
77
+ if not self.api_key:
78
+ raise ValorantApiError(
79
+ f"Missing API key. Get a free key at {SIGNUP_URL} (or https://valorant-api.org/) "
80
+ "and set CITO_API_KEY (or pass api_key=)."
81
+ )
82
+
83
+ def _build_url(self, path: str, params: Optional[Dict[str, Any]] = None) -> str:
84
+ clean_path = path if path.startswith("/") else f"/{path}"
85
+ if self.base_url.endswith("/valorant"):
86
+ if clean_path == "/valorant":
87
+ clean_path = "/"
88
+ elif clean_path.startswith("/valorant/"):
89
+ clean_path = clean_path[len("/valorant"):]
90
+ url = self.base_url if clean_path in ("", "/") else self.base_url + clean_path
91
+ if clean_path == "/" and not url.endswith("/"):
92
+ url += "/"
93
+ cleaned = _clean_params(params)
94
+ if cleaned:
95
+ url += "?" + urllib.parse.urlencode(cleaned)
96
+ return url
97
+
98
+ def _sample_csv_url(self, kind: str) -> str:
99
+ if self.base_url.endswith("/valorant"):
100
+ root = self.base_url[: -len("/valorant")]
101
+ else:
102
+ root = self.base_url
103
+ return f"{root}/exports/sample/valorant/{kind}.csv"
104
+
105
+ def _fetch_text(self, url: str) -> str:
106
+ req = urllib.request.Request(
107
+ url,
108
+ headers={
109
+ "Accept": "text/csv, text/plain, */*",
110
+ "User-Agent": f"valorant-esports-api-python/{__version__}",
111
+ },
112
+ )
113
+ try:
114
+ with urllib.request.urlopen(req, timeout=self.timeout) as res:
115
+ return res.read().decode("utf-8")
116
+ except urllib.error.HTTPError as err:
117
+ raise ValorantApiError(f"Request failed with status {err.code}", err.code, None) from None
118
+
119
+ def get(self, path: str, params: Optional[Dict[str, Any]] = None, raw: bool = False) -> Any:
120
+ """Call any endpoint. Returns `data`, or the full envelope (data + meta) when raw=True."""
121
+ url = self._build_url(path, params)
122
+ req = urllib.request.Request(
123
+ url,
124
+ headers={
125
+ "X-API-Key": str(self.api_key),
126
+ "Accept": "application/json",
127
+ "User-Agent": f"valorant-esports-api-python/{__version__}",
128
+ },
129
+ )
130
+ try:
131
+ with urllib.request.urlopen(req, timeout=self.timeout) as res:
132
+ body = json.loads(res.read().decode("utf-8"))
133
+ except urllib.error.HTTPError as err:
134
+ try:
135
+ body = json.loads(err.read().decode("utf-8"))
136
+ except Exception:
137
+ body = None
138
+ message = ((body or {}).get("error") or {}).get("message") if isinstance(body, dict) else None
139
+ raise ValorantApiError(message or f"Request failed with status {err.code}", err.code, body) from None
140
+ if isinstance(body, dict) and body.get("success") is False:
141
+ raise ValorantApiError(((body.get("error") or {}).get("message")) or "Request failed", 200, body)
142
+ return body if raw else (body.get("data") if isinstance(body, dict) else body)
143
+
144
+ # ---- Overview ----
145
+ def overview(self) -> Any:
146
+ """Return Valorant API overview counts and available endpoint list."""
147
+ return self.get("/")
148
+
149
+ # ---- Matches ----
150
+ def live(
151
+ self,
152
+ limit: Optional[int] = None,
153
+ offset: Optional[int] = None,
154
+ page: Optional[int] = None,
155
+ include_games: Optional[bool] = None,
156
+ ) -> Any:
157
+ """Return live Valorant matches currently in progress."""
158
+ return self.get(
159
+ "/matches/live",
160
+ {"limit": limit, "offset": offset, "page": page, "include_games": include_games},
161
+ )
162
+
163
+ def upcoming(
164
+ self,
165
+ event_id: Optional[str] = None,
166
+ team_id: Optional[str] = None,
167
+ date: Optional[str] = None,
168
+ date_from: Optional[str] = None,
169
+ date_to: Optional[str] = None,
170
+ q: Optional[str] = None,
171
+ limit: int = 50,
172
+ offset: Optional[int] = None,
173
+ page: Optional[int] = None,
174
+ include_games: Optional[bool] = None,
175
+ **extra: Any,
176
+ ) -> Any:
177
+ """Return upcoming scheduled Valorant matches."""
178
+ query: Dict[str, Any] = {
179
+ "event_id": event_id,
180
+ "team_id": team_id,
181
+ "date": date,
182
+ "from": extra.pop("from", date_from),
183
+ "to": extra.pop("to", date_to),
184
+ "q": q,
185
+ "limit": limit,
186
+ "offset": offset,
187
+ "page": page,
188
+ "include_games": include_games,
189
+ **extra,
190
+ }
191
+ return self.get("/matches/upcoming", query)
192
+
193
+ def results(
194
+ self,
195
+ event_id: Optional[str] = None,
196
+ team_id: Optional[str] = None,
197
+ date: Optional[str] = None,
198
+ date_from: Optional[str] = None,
199
+ date_to: Optional[str] = None,
200
+ q: Optional[str] = None,
201
+ limit: int = 50,
202
+ offset: Optional[int] = None,
203
+ page: Optional[int] = None,
204
+ include_games: Optional[bool] = None,
205
+ **extra: Any,
206
+ ) -> Any:
207
+ """Return completed Valorant match results, newest first."""
208
+ query: Dict[str, Any] = {
209
+ "event_id": event_id,
210
+ "team_id": team_id,
211
+ "date": date,
212
+ "from": extra.pop("from", date_from),
213
+ "to": extra.pop("to", date_to),
214
+ "q": q,
215
+ "limit": limit,
216
+ "offset": offset,
217
+ "page": page,
218
+ "include_games": include_games,
219
+ **extra,
220
+ }
221
+ return self.get("/matches/results", query)
222
+
223
+ def matches(
224
+ self,
225
+ status: Optional[str] = None,
226
+ event_id: Optional[str] = None,
227
+ team_id: Optional[str] = None,
228
+ date: Optional[str] = None,
229
+ date_from: Optional[str] = None,
230
+ date_to: Optional[str] = None,
231
+ q: Optional[str] = None,
232
+ limit: int = 50,
233
+ offset: Optional[int] = None,
234
+ page: Optional[int] = None,
235
+ include_games: Optional[bool] = None,
236
+ **extra: Any,
237
+ ) -> Any:
238
+ """List Valorant matches filtered by status, event, team, date range, or search query."""
239
+ query: Dict[str, Any] = {
240
+ "status": status,
241
+ "event_id": event_id,
242
+ "team_id": team_id,
243
+ "date": date,
244
+ "from": extra.pop("from", date_from),
245
+ "to": extra.pop("to", date_to),
246
+ "q": q,
247
+ "limit": limit,
248
+ "offset": offset,
249
+ "page": page,
250
+ "include_games": include_games,
251
+ **extra,
252
+ }
253
+ return self.get("/matches", query)
254
+
255
+ def match(self, match_id: str) -> Any:
256
+ """Return full match detail including veto, streams, and games."""
257
+ return self.get(f"/matches/{_q(match_id)}")
258
+
259
+ def match_games(self, match_id: str) -> Any:
260
+ """Return per-map games with rounds, economy, and player stats (ACS, K/D/A, ADR, KAST, HS%, FK/FD)."""
261
+ return self.get(f"/matches/{_q(match_id)}/games")
262
+
263
+ # ---- Teams ----
264
+ def teams(
265
+ self,
266
+ q: Optional[str] = None,
267
+ country: Optional[str] = None,
268
+ region: Optional[str] = None,
269
+ limit: int = 50,
270
+ offset: Optional[int] = None,
271
+ page: Optional[int] = None,
272
+ ) -> Any:
273
+ """List or search Valorant teams."""
274
+ return self.get(
275
+ "/teams",
276
+ {"q": q, "country": country, "region": region, "limit": limit, "offset": offset, "page": page},
277
+ )
278
+
279
+ def team(self, team_id: str) -> Any:
280
+ """Return team profile, ranking, record, active roster, and staff."""
281
+ return self.get(f"/teams/{_q(team_id)}")
282
+
283
+ def team_matches(
284
+ self,
285
+ team_id: str,
286
+ status: Optional[str] = None,
287
+ limit: int = 50,
288
+ offset: Optional[int] = None,
289
+ page: Optional[int] = None,
290
+ include_games: Optional[bool] = None,
291
+ ) -> Any:
292
+ """Return matches for a specific Valorant team."""
293
+ return self.get(
294
+ f"/teams/{_q(team_id)}/matches",
295
+ {"status": status, "limit": limit, "offset": offset, "page": page, "include_games": include_games},
296
+ )
297
+
298
+ # ---- Players ----
299
+ def players(
300
+ self,
301
+ q: Optional[str] = None,
302
+ team_id: Optional[str] = None,
303
+ country: Optional[str] = None,
304
+ role: Optional[str] = None,
305
+ limit: int = 50,
306
+ offset: Optional[int] = None,
307
+ page: Optional[int] = None,
308
+ ) -> Any:
309
+ """List or search Valorant players."""
310
+ return self.get(
311
+ "/players",
312
+ {"q": q, "team_id": team_id, "country": country, "role": role, "limit": limit, "offset": offset, "page": page},
313
+ )
314
+
315
+ def player(self, player_id: str) -> Any:
316
+ """Return player profile including `career_summary` and `agents` stats."""
317
+ return self.get(f"/players/{_q(player_id)}")
318
+
319
+ def player_matches(
320
+ self,
321
+ player_id: str,
322
+ limit: int = 50,
323
+ offset: Optional[int] = None,
324
+ page: Optional[int] = None,
325
+ include_games: Optional[bool] = None,
326
+ ) -> Any:
327
+ """Return recent and historical matches for a Valorant player."""
328
+ return self.get(
329
+ f"/players/{_q(player_id)}/matches",
330
+ {"limit": limit, "offset": offset, "page": page, "include_games": include_games},
331
+ )
332
+
333
+ # ---- Events ----
334
+ def events(
335
+ self,
336
+ status: Optional[str] = None,
337
+ region: Optional[str] = None,
338
+ q: Optional[str] = None,
339
+ limit: int = 50,
340
+ offset: Optional[int] = None,
341
+ page: Optional[int] = None,
342
+ ) -> Any:
343
+ """List Valorant tournaments and events."""
344
+ return self.get(
345
+ "/events",
346
+ {"status": status, "region": region, "q": q, "limit": limit, "offset": offset, "page": page},
347
+ )
348
+
349
+ def event(self, event_id: str) -> Any:
350
+ """Return event details, participating teams, and prize distribution."""
351
+ return self.get(f"/events/{_q(event_id)}")
352
+
353
+ def event_matches(
354
+ self,
355
+ event_id: str,
356
+ status: Optional[str] = None,
357
+ limit: int = 50,
358
+ offset: Optional[int] = None,
359
+ page: Optional[int] = None,
360
+ include_games: Optional[bool] = None,
361
+ ) -> Any:
362
+ """Return all matches belonging to a Valorant event."""
363
+ return self.get(
364
+ f"/events/{_q(event_id)}/matches",
365
+ {"status": status, "limit": limit, "offset": offset, "page": page, "include_games": include_games},
366
+ )
367
+
368
+ # ---- Rankings & Transfers ----
369
+ def rankings(
370
+ self,
371
+ region: Optional[str] = None,
372
+ date: Optional[str] = None,
373
+ limit: int = 50,
374
+ offset: Optional[int] = None,
375
+ page: Optional[int] = None,
376
+ ) -> Any:
377
+ """Return regional Valorant team rankings."""
378
+ return self.get(
379
+ "/rankings",
380
+ {"region": region, "date": date, "limit": limit, "offset": offset, "page": page},
381
+ )
382
+
383
+ def transfers(
384
+ self,
385
+ team_id: Optional[str] = None,
386
+ player_id: Optional[str] = None,
387
+ action: Optional[str] = None,
388
+ date_from: Optional[str] = None,
389
+ date_to: Optional[str] = None,
390
+ limit: int = 50,
391
+ offset: Optional[int] = None,
392
+ page: Optional[int] = None,
393
+ **extra: Any,
394
+ ) -> Any:
395
+ """Return Valorant roster transfers and signings."""
396
+ query: Dict[str, Any] = {
397
+ "team_id": team_id,
398
+ "player_id": player_id,
399
+ "action": action,
400
+ "from": extra.pop("from", date_from),
401
+ "to": extra.pop("to", date_to),
402
+ "limit": limit,
403
+ "offset": offset,
404
+ "page": page,
405
+ **extra,
406
+ }
407
+ return self.get("/transfers", query)
408
+
409
+ # ---- Public Sample CSVs ----
410
+ def sample_matches_csv(self) -> str:
411
+ """Fetch the public sample Valorant matches CSV (no API key required)."""
412
+ return self._fetch_text(self._sample_csv_url("matches"))
413
+
414
+ def sample_players_csv(self) -> str:
415
+ """Fetch the public sample Valorant players CSV (no API key required)."""
416
+ return self._fetch_text(self._sample_csv_url("players"))
417
+
418
+ # ---- Live WebSocket Helpers ----
419
+ def ws_url(self, api_key: Optional[str] = None) -> str:
420
+ """Return the WebSocket URL for live Valorant match updates.
421
+
422
+ Pass api_key for browser/OBS query auth (?api_key=...), or omit it when
423
+ connecting from a server/bot with the X-API-Key header.
424
+ """
425
+ if self.base_url.startswith("https://"):
426
+ ws_base = "wss://" + self.base_url[len("https://"):]
427
+ elif self.base_url.startswith("http://"):
428
+ ws_base = "ws://" + self.base_url[len("http://"):]
429
+ else:
430
+ ws_base = self.base_url
431
+ if not ws_base.endswith("/valorant"):
432
+ ws_base += "/valorant"
433
+ url = f"{ws_base}/live/ws"
434
+ if api_key:
435
+ url += f"?api_key={_q(api_key)}"
436
+ return url
437
+
438
+ @staticmethod
439
+ def ws_subscribe_payload(rooms: Optional[Sequence[str]] = None) -> Dict[str, Any]:
440
+ """Build the WebSocket subscribe payload using the required `rooms` key."""
441
+ selected = [str(r) for r in rooms if r] if rooms else ["all"]
442
+ if not selected:
443
+ selected = ["all"]
444
+ return {"action": "subscribe", "rooms": selected}
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.4
2
+ Name: valorant-esports-api
3
+ Version: 1.0.0
4
+ Summary: Official Valorant esports API client for live VCT scores, WebSocket rooms, historical matches, per-map player stats, rankings, teams, events, and sample CSVs. Standard library only.
5
+ Author: Cito API
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://valorant-api.org/
8
+ Project-URL: Documentation, https://citoapi.com/docs/api/valorant/live/
9
+ Project-URL: Source, https://github.com/Cito-GG/valorant-esports-api
10
+ Project-URL: Issues, https://github.com/Cito-GG/valorant-esports-api/issues
11
+ Project-URL: Get a free API key, https://citoapi.com/signup?game=valorant&utm_source=npm-pypi&utm_medium=referral&utm_campaign=valorant-esports-api
12
+ Keywords: valorant,valorant-api,valorant-esports,vct,live-valorant-api,historical-valorant-api,websocket,esports
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Games/Entertainment
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.8
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Dynamic: license-file
23
+
24
+ # valorant-esports-api (Python)
25
+
26
+ [![PyPI](https://img.shields.io/pypi/v/valorant-esports-api)](https://pypi.org/project/valorant-esports-api/) [![license](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
27
+
28
+ Official Python client for the **Valorant esports API** at [valorant-api.org](https://valorant-api.org/) and [citoapi.com/valorant/](https://citoapi.com/valorant/). Zero runtime dependencies (Python 3.8+ standard library only).
29
+
30
+ Use one client as both a **live Valorant API** and a **historical Valorant API** across `71,596` matches, `6,081` teams, `43,029` players, and `3,099` events (VCT 2021-2026, Challengers, and Ascension):
31
+
32
+ - Live match scores, schedules, results, and match detail (`veto`, `streams`, `games`)
33
+ - Per-map game telemetry: round timelines, economy conversions, ACS, K/D/A, ADR, KAST, HS%, and FK/FD
34
+ - Teams, active rosters, coaching staff, and regional rankings
35
+ - Player profiles (`career_summary` and `agents` stats) and match logs
36
+ - Events/tournaments and roster transfers
37
+ - **VCT WebSocket** URL and `"rooms"` subscription payload builders (`wss://api.citoapi.com/api/v1/valorant/live/ws`)
38
+ - Public sample CSV downloads (`matches.csv` and `players.csv`, no API key required)
39
+
40
+ > **Get a free API key** (500 requests/month, no card): **[Sign up for Valorant API](https://citoapi.com/signup?game=valorant&utm_source=npm-pypi&utm_medium=referral&utm_campaign=valorant-esports-api)**
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install valorant-esports-api
46
+ ```
47
+
48
+ ## Quickstart
49
+
50
+ ```python
51
+ import json
52
+ from valorant_esports_api import ValorantApi
53
+
54
+ api = ValorantApi() # reads CITO_API_KEY from environment
55
+
56
+ # 1. Live Valorant matches
57
+ live = api.live()
58
+ for m in live["matches"]:
59
+ t = m["teams"]
60
+ s = m["score"]
61
+ print(f"{t['team1_name']} {s['team1']}-{s['team2']} {t['team2_name']} ({m['event_name']})")
62
+
63
+ # 2. Historical Valorant matches with filters
64
+ history = api.matches(
65
+ status="Completed",
66
+ date_from="2026-01-01",
67
+ date_to="2026-03-01",
68
+ limit=25,
69
+ )
70
+ first_match = history["matches"][0]
71
+ games = api.match_games(first_match["id"])
72
+
73
+ # 3. Player career summary and per-agent stats
74
+ player = api.player("tenz")
75
+ print(player["career_summary"])
76
+ print(player["agents"][:3])
77
+
78
+ # 4. Regional team rankings and transfers
79
+ emea_rankings = api.rankings(region="europe", limit=10)
80
+ recent_transfers = api.transfers(limit=20)
81
+ ```
82
+
83
+ ## Public Sample CSVs (No API Key Required)
84
+
85
+ ```python
86
+ matches_csv = api.sample_matches_csv()
87
+ players_csv = api.sample_players_csv()
88
+ print(matches_csv.splitlines()[:5])
89
+ ```
90
+
91
+ Direct URLs:
92
+
93
+ - `https://api.citoapi.com/api/v1/exports/sample/valorant/matches.csv`
94
+ - `https://api.citoapi.com/api/v1/exports/sample/valorant/players.csv`
95
+
96
+ ## Live VCT WebSocket Helper
97
+
98
+ The **VCT WebSocket** endpoint is `wss://api.citoapi.com/api/v1/valorant/live/ws` (available on Pro + `$15/mo` Live WebSockets add-on, Scale, and Business CSV). Authenticate via the `X-API-Key` header for servers/bots, or `?api_key=<key>` for browser sources.
99
+
100
+ ```python
101
+ import json
102
+
103
+ ws_url = api.ws_url() # or api.ws_url("your_key") for ?api_key=... query auth
104
+ subscribe_msg = api.ws_subscribe_payload(["all"]) # {"action": "subscribe", "rooms": ["all"]}
105
+ match_msg = api.ws_subscribe_payload(["match:val-match-12345"])
106
+
107
+ print(ws_url)
108
+ print(json.dumps(subscribe_msg))
109
+ print(json.dumps(match_msg))
110
+ ```
111
+
112
+ Note: Subscribe messages use the `"rooms"` key (`{"action": "subscribe", "rooms": ["all"]}`). Metering is `0` requests per pushed event, `1` request on upgrade + `1` request per `15s` open.
113
+
114
+ ## Methods
115
+
116
+ All methods return the unwrapped `data` object by default; pass `raw=True` to `api.get(path, params, raw=True)` for the full `{success, data, meta}` envelope.
117
+
118
+ | Area | Methods |
119
+ |---|---|
120
+ | Overview | `overview()` |
121
+ | Matches | `live(...)`, `upcoming(...)`, `results(...)`, `matches(status=..., event_id=..., team_id=..., date_from=..., date_to=..., limit=..., offset=...)`, `match(match_id)`, `match_games(match_id)` |
122
+ | Teams | `teams(...)`, `team(team_id)`, `team_matches(team_id, ...)` |
123
+ | Players | `players(...)`, `player(player_id)`, `player_matches(player_id, ...)` |
124
+ | Events | `events(...)`, `event(event_id)`, `event_matches(event_id, ...)` |
125
+ | Rankings & Transfers | `rankings(region=..., date=..., limit=...)`, `transfers(...)` |
126
+ | Sample CSVs | `sample_matches_csv()`, `sample_players_csv()` |
127
+ | WebSocket | `ws_url(api_key=None)`, `ws_subscribe_payload(rooms=None)` |
128
+ | Escape hatch | `get(path, params=None, raw=False)` |
129
+
130
+ Errors raise `ValorantApiError` with `.status`, `.code`, and `.body`.
131
+
132
+ ## Pricing & Tiers
133
+
134
+ - **Free** (`$0/mo`, `500` reqs/mo) & **Starter** (`$15/mo`, `10,000` reqs/mo): REST with `60s` live delay, full historical access.
135
+ - **Pro** (`$59/mo`, `250,000` reqs/mo): `0s` live REST + optional `+$15/mo` Live WebSockets add-on (unlocks `/live/ws` and `/live/stream`).
136
+ - **Scale** (`$100/mo`, `1,000,000` reqs/mo): `0s` live REST + WebSocket & SSE included.
137
+ - **Business CSV** (`$299/mo`, `3,000,000` reqs/mo): `0s` live REST + WebSocket & SSE included + full historical CSV exports.
138
+
139
+ ## Links
140
+
141
+ - Live Valorant API Docs: https://citoapi.com/docs/api/valorant/live/
142
+ - Live WebSocket Docs: https://citoapi.com/docs/api/valorant/live/websocket/
143
+ - Historical Valorant API Docs: https://citoapi.com/docs/api/valorant/historical/
144
+ - Historical CSV Dataset: https://valorant-api.org/historical-csv-dataset/
145
+ - Pricing: https://citoapi.com/pricing/
146
+ - GitHub Monorepo: https://github.com/Cito-GG/valorant-esports-api
147
+
148
+ MIT licensed.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/valorant_esports_api/__init__.py
5
+ src/valorant_esports_api/py.typed
6
+ src/valorant_esports_api.egg-info/PKG-INFO
7
+ src/valorant_esports_api.egg-info/SOURCES.txt
8
+ src/valorant_esports_api.egg-info/dependency_links.txt
9
+ src/valorant_esports_api.egg-info/top_level.txt
10
+ tests/test_client.py
@@ -0,0 +1,263 @@
1
+ """Unit tests for valorant-esports-api using a local mock HTTP server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ import threading
9
+ import unittest
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List
13
+ from urllib.parse import parse_qs, urlparse
14
+
15
+ SRC_DIR = str(Path(__file__).resolve().parents[1] / "src")
16
+ if SRC_DIR not in sys.path:
17
+ sys.path.insert(0, SRC_DIR)
18
+
19
+ from valorant_esports_api import ( # noqa: E402
20
+ DEFAULT_BASE_URL,
21
+ DEFAULT_WS_URL,
22
+ SAMPLE_MATCHES_CSV_URL,
23
+ SAMPLE_PLAYERS_CSV_URL,
24
+ ValorantApi,
25
+ ValorantApiError,
26
+ )
27
+
28
+
29
+ class _MockState:
30
+ def __init__(self) -> None:
31
+ self.requests: List[Dict[str, Any]] = []
32
+ self.status_code = 200
33
+ self.body: Any = {"success": True, "data": {}, "meta": {"count": 0}}
34
+ self.text_body: str | None = None
35
+
36
+
37
+ def _make_handler(state: _MockState):
38
+ class Handler(BaseHTTPRequestHandler):
39
+ def do_GET(self) -> None: # noqa: N802
40
+ parsed = urlparse(self.path)
41
+ state.requests.append(
42
+ {
43
+ "path": parsed.path,
44
+ "query": parse_qs(parsed.query, keep_blank_values=True),
45
+ "headers": {k.lower(): v for k, v in self.headers.items()},
46
+ }
47
+ )
48
+ self.send_response(state.status_code)
49
+ if state.text_body is not None:
50
+ self.send_header("Content-Type", "text/csv; charset=utf-8")
51
+ self.end_headers()
52
+ self.wfile.write(state.text_body.encode("utf-8"))
53
+ else:
54
+ self.send_header("Content-Type", "application/json")
55
+ self.end_headers()
56
+ self.wfile.write(json.dumps(state.body).encode("utf-8"))
57
+
58
+ def log_message(self, format: str, *args: Any) -> None:
59
+ return
60
+
61
+ return Handler
62
+
63
+
64
+ class ValorantApiTests(unittest.TestCase):
65
+ def setUp(self) -> None:
66
+ self.state = _MockState()
67
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), _make_handler(self.state))
68
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
69
+ self.thread.start()
70
+ host, port = self.server.server_address
71
+ self.base_url = f"http://{host}:{port}/api/v1/valorant"
72
+ self.api = ValorantApi(api_key="test_val_key", base_url=self.base_url)
73
+
74
+ def tearDown(self) -> None:
75
+ self.server.shutdown()
76
+ self.server.server_close()
77
+
78
+ def test_constants(self) -> None:
79
+ self.assertEqual(DEFAULT_BASE_URL, "https://api.citoapi.com/api/v1/valorant")
80
+ self.assertEqual(DEFAULT_WS_URL, "wss://api.citoapi.com/api/v1/valorant/live/ws")
81
+ self.assertTrue(SAMPLE_MATCHES_CSV_URL.endswith("/exports/sample/valorant/matches.csv"))
82
+ self.assertTrue(SAMPLE_PLAYERS_CSV_URL.endswith("/exports/sample/valorant/players.csv"))
83
+
84
+ def test_missing_key_raises_with_signup_link(self) -> None:
85
+ old = os.environ.pop("CITO_API_KEY", None)
86
+ try:
87
+ with self.assertRaises(ValorantApiError) as ctx:
88
+ ValorantApi(api_key="")
89
+ self.assertIn("valorant-api.org", str(ctx.exception))
90
+ finally:
91
+ if old is not None:
92
+ os.environ["CITO_API_KEY"] = old
93
+
94
+ def test_headers_and_unwrapping(self) -> None:
95
+ self.state.body = {
96
+ "success": True,
97
+ "data": {"entity_type": "valorant_overview", "counts": {"matches": 71596}},
98
+ "meta": {"count": 1},
99
+ }
100
+ data = self.api.overview()
101
+ self.assertEqual(data["counts"]["matches"], 71596)
102
+ req = self.state.requests[-1]
103
+ self.assertEqual(req["path"], "/api/v1/valorant/")
104
+ self.assertEqual(req["headers"]["x-api-key"], "test_val_key")
105
+ self.assertEqual(req["headers"]["accept"], "application/json")
106
+
107
+ raw = self.api.get("/matches/live", raw=True)
108
+ self.assertEqual(raw["meta"]["count"], 1)
109
+
110
+ def test_all_endpoint_routes_and_params(self) -> None:
111
+ self.state.body = {"success": True, "data": {"ok": True}, "meta": {}}
112
+
113
+ self.api.live(limit=10, offset=0, include_games=False)
114
+ req = self.state.requests[-1]
115
+ self.assertEqual(req["path"], "/api/v1/valorant/matches/live")
116
+ self.assertEqual(req["query"], {"limit": ["10"], "offset": ["0"], "include_games": ["false"]})
117
+
118
+ self.api.upcoming(event_id="val-event-1", limit=20)
119
+ req = self.state.requests[-1]
120
+ self.assertEqual(req["path"], "/api/v1/valorant/matches/upcoming")
121
+ self.assertEqual(req["query"], {"event_id": ["val-event-1"], "limit": ["20"]})
122
+
123
+ self.api.results(team_id="val-team-2", limit=15)
124
+ req = self.state.requests[-1]
125
+ self.assertEqual(req["path"], "/api/v1/valorant/matches/results")
126
+ self.assertEqual(req["query"], {"team_id": ["val-team-2"], "limit": ["15"]})
127
+
128
+ self.api.matches(
129
+ status="Completed",
130
+ event_id="val-event-1",
131
+ team_id="val-team-2",
132
+ date_from="2026-01-01",
133
+ date_to="2026-02-01",
134
+ limit=25,
135
+ offset=50,
136
+ )
137
+ req = self.state.requests[-1]
138
+ self.assertEqual(req["path"], "/api/v1/valorant/matches")
139
+ self.assertEqual(
140
+ req["query"],
141
+ {
142
+ "status": ["Completed"],
143
+ "event_id": ["val-event-1"],
144
+ "team_id": ["val-team-2"],
145
+ "from": ["2026-01-01"],
146
+ "to": ["2026-02-01"],
147
+ "limit": ["25"],
148
+ "offset": ["50"],
149
+ },
150
+ )
151
+
152
+ self.api.match("val-match-123")
153
+ self.assertEqual(self.state.requests[-1]["path"], "/api/v1/valorant/matches/val-match-123")
154
+
155
+ self.api.match_games("val-match-123")
156
+ self.assertEqual(self.state.requests[-1]["path"], "/api/v1/valorant/matches/val-match-123/games")
157
+
158
+ self.api.teams(q="fnatic", region="emea", limit=10)
159
+ req = self.state.requests[-1]
160
+ self.assertEqual(req["path"], "/api/v1/valorant/teams")
161
+ self.assertEqual(req["query"], {"q": ["fnatic"], "region": ["emea"], "limit": ["10"]})
162
+
163
+ self.api.team("fnatic")
164
+ self.assertEqual(self.state.requests[-1]["path"], "/api/v1/valorant/teams/fnatic")
165
+
166
+ self.api.team_matches("fnatic", status="Completed", limit=5)
167
+ req = self.state.requests[-1]
168
+ self.assertEqual(req["path"], "/api/v1/valorant/teams/fnatic/matches")
169
+ self.assertEqual(req["query"], {"status": ["Completed"], "limit": ["5"]})
170
+
171
+ self.api.players(q="tenz", role="duelist", limit=10)
172
+ req = self.state.requests[-1]
173
+ self.assertEqual(req["path"], "/api/v1/valorant/players")
174
+ self.assertEqual(req["query"], {"q": ["tenz"], "role": ["duelist"], "limit": ["10"]})
175
+
176
+ self.api.player("tenz")
177
+ self.assertEqual(self.state.requests[-1]["path"], "/api/v1/valorant/players/tenz")
178
+
179
+ self.api.player_matches("tenz", limit=5, include_games=True)
180
+ req = self.state.requests[-1]
181
+ self.assertEqual(req["path"], "/api/v1/valorant/players/tenz/matches")
182
+ self.assertEqual(req["query"], {"limit": ["5"], "include_games": ["true"]})
183
+
184
+ self.api.events(status="live", region="americas", limit=10)
185
+ req = self.state.requests[-1]
186
+ self.assertEqual(req["path"], "/api/v1/valorant/events")
187
+ self.assertEqual(req["query"], {"status": ["live"], "region": ["americas"], "limit": ["10"]})
188
+
189
+ self.api.event("vct-masters")
190
+ self.assertEqual(self.state.requests[-1]["path"], "/api/v1/valorant/events/vct-masters")
191
+
192
+ self.api.event_matches("vct-masters", limit=12)
193
+ req = self.state.requests[-1]
194
+ self.assertEqual(req["path"], "/api/v1/valorant/events/vct-masters/matches")
195
+ self.assertEqual(req["query"], {"limit": ["12"]})
196
+
197
+ self.api.rankings(region="europe", limit=20)
198
+ req = self.state.requests[-1]
199
+ self.assertEqual(req["path"], "/api/v1/valorant/rankings")
200
+ self.assertEqual(req["query"], {"region": ["europe"], "limit": ["20"]})
201
+
202
+ self.api.transfers(team_id="val-team-1", action="join", date_from="2026-01-01", limit=15)
203
+ req = self.state.requests[-1]
204
+ self.assertEqual(req["path"], "/api/v1/valorant/transfers")
205
+ self.assertEqual(
206
+ req["query"],
207
+ {"team_id": ["val-team-1"], "action": ["join"], "from": ["2026-01-01"], "limit": ["15"]},
208
+ )
209
+
210
+ def test_get_handles_valorant_prefix_and_escaping(self) -> None:
211
+ self.state.body = {"success": True, "data": {"ok": True}}
212
+ self.api.get("/valorant/matches/a/b")
213
+ self.assertEqual(self.state.requests[-1]["path"], "/api/v1/valorant/matches/a/b")
214
+ self.api.match("val-match/1")
215
+ self.assertEqual(self.state.requests[-1]["path"], "/api/v1/valorant/matches/val-match%2F1")
216
+
217
+ def test_error_handling(self) -> None:
218
+ self.state.status_code = 401
219
+ self.state.body = {"success": False, "error": {"code": "UNAUTHORIZED", "message": "Invalid API key"}}
220
+ with self.assertRaises(ValorantApiError) as ctx:
221
+ self.api.live()
222
+ self.assertEqual(ctx.exception.status, 401)
223
+ self.assertEqual(ctx.exception.code, "UNAUTHORIZED")
224
+ self.assertIn("Invalid API key", str(ctx.exception))
225
+
226
+ self.state.status_code = 200
227
+ self.state.body = {"success": False, "error": {"code": "NOT_FOUND", "message": "Match not found"}}
228
+ with self.assertRaises(ValorantApiError) as ctx2:
229
+ self.api.match("missing")
230
+ self.assertEqual(ctx2.exception.status, 200)
231
+ self.assertEqual(ctx2.exception.code, "NOT_FOUND")
232
+
233
+ def test_sample_csv_helpers(self) -> None:
234
+ self.state.text_body = "id,status\nval-match-1,Completed\n"
235
+ csv_text = self.api.sample_matches_csv()
236
+ self.assertIn("val-match-1", csv_text)
237
+ req = self.state.requests[-1]
238
+ self.assertEqual(req["path"], "/api/v1/exports/sample/valorant/matches.csv")
239
+ self.assertNotIn("x-api-key", req["headers"])
240
+
241
+ self.state.text_body = "player_id,handle\nval-player-1,TenZ\n"
242
+ players_csv = self.api.sample_players_csv()
243
+ self.assertIn("TenZ", players_csv)
244
+ self.assertEqual(self.state.requests[-1]["path"], "/api/v1/exports/sample/valorant/players.csv")
245
+
246
+ def test_ws_helpers(self) -> None:
247
+ prod_api = ValorantApi(api_key="secret")
248
+ self.assertEqual(prod_api.ws_url(), "wss://api.citoapi.com/api/v1/valorant/live/ws")
249
+ self.assertEqual(
250
+ prod_api.ws_url("obs key"),
251
+ "wss://api.citoapi.com/api/v1/valorant/live/ws?api_key=obs%20key",
252
+ )
253
+ self.assertEqual(
254
+ self.api.ws_subscribe_payload(),
255
+ {"action": "subscribe", "rooms": ["all"]},
256
+ )
257
+ payload = ValorantApi.ws_subscribe_payload(["match:val-match-12345"])
258
+ self.assertEqual(payload, {"action": "subscribe", "rooms": ["match:val-match-12345"]})
259
+ self.assertNotIn("channels", payload)
260
+
261
+
262
+ if __name__ == "__main__":
263
+ unittest.main()