blizzardapi2 4.0.2__tar.gz → 5.1.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.
Files changed (79) hide show
  1. blizzardapi2-5.1.0/.agents/setup +27 -0
  2. blizzardapi2-5.1.0/.github/workflows/pr_agent.yml +24 -0
  3. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/.github/workflows/python-package.yml +5 -1
  4. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/.gitignore +4 -1
  5. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/.pre-commit-config.yaml +6 -0
  6. blizzardapi2-5.1.0/.release-it.cjs +55 -0
  7. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/CLAUDE.md +5 -3
  8. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/CONTRIBUTING.md +2 -2
  9. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/PKG-INFO +34 -25
  10. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/README.md +31 -22
  11. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/__init__.py +1 -0
  12. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/api.py +55 -50
  13. blizzardapi2-5.1.0/blizzardapi2/battlenet/__init__.py +5 -0
  14. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/battlenet/battlenet_api.py +8 -1
  15. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/battlenet/battlenet_oauth_api.py +1 -1
  16. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/blizzard_api.py +33 -5
  17. blizzardapi2-5.1.0/blizzardapi2/diablo3/__init__.py +4 -0
  18. blizzardapi2-5.1.0/blizzardapi2/diablo3/diablo3_api.py +44 -0
  19. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/diablo3/diablo3_game_data_api.py +1 -1
  20. blizzardapi2-5.1.0/blizzardapi2/endpoint.py +142 -0
  21. blizzardapi2-5.1.0/blizzardapi2/hearthstone/__init__.py +4 -0
  22. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/hearthstone/hearthstone_api.py +9 -3
  23. blizzardapi2-5.1.0/blizzardapi2/starcraft2/__init__.py +4 -0
  24. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/starcraft2/starcraft2_api.py +17 -5
  25. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/starcraft2/starcraft2_community_api.py +1 -1
  26. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/starcraft2/starcraft2_game_data_api.py +1 -1
  27. blizzardapi2-5.1.0/blizzardapi2/token_manager.py +60 -0
  28. blizzardapi2-5.1.0/blizzardapi2/wow/__init__.py +4 -0
  29. blizzardapi2-5.1.0/blizzardapi2/wow/wow_api.py +45 -0
  30. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/wow/wow_game_data_api.py +2 -1
  31. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/wow/wow_profile_api.py +42 -42
  32. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2.egg-info/PKG-INFO +34 -25
  33. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2.egg-info/SOURCES.txt +7 -1
  34. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2.egg-info/requires.txt +2 -2
  35. blizzardapi2-5.1.0/docs/EXAMPLES.md +76 -0
  36. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/docs/battlenet/README.md +37 -24
  37. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/docs/diablo3/README.md +35 -21
  38. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/docs/hearthstone/README.md +58 -23
  39. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/docs/starcraft2/README.md +78 -42
  40. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/docs/wow/README.md +52 -45
  41. blizzardapi2-5.1.0/examples/custom_session.py +108 -0
  42. blizzardapi2-5.1.0/examples/oauth_server.py +81 -0
  43. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/package-lock.json +439 -639
  44. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/package.json +3 -3
  45. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/pyproject.toml +4 -3
  46. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/tests/conftest.py +12 -5
  47. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/tests/test_base_api.py +328 -45
  48. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/tests/test_battlenet.py +13 -13
  49. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/tests/test_diablo3.py +14 -11
  50. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/tests/test_hearthstone.py +14 -11
  51. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/tests/test_starcraft2.py +23 -16
  52. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/tests/test_wow.py +24 -19
  53. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/uv.lock +44 -44
  54. blizzardapi2-4.0.2/.release-it.json +0 -24
  55. blizzardapi2-4.0.2/blizzardapi2/battlenet/__init__.py +0 -1
  56. blizzardapi2-4.0.2/blizzardapi2/diablo3/__init__.py +0 -1
  57. blizzardapi2-4.0.2/blizzardapi2/diablo3/diablo3_api.py +0 -31
  58. blizzardapi2-4.0.2/blizzardapi2/endpoint.py +0 -81
  59. blizzardapi2-4.0.2/blizzardapi2/hearthstone/__init__.py +0 -1
  60. blizzardapi2-4.0.2/blizzardapi2/starcraft2/__init__.py +0 -1
  61. blizzardapi2-4.0.2/blizzardapi2/wow/__init__.py +0 -1
  62. blizzardapi2-4.0.2/blizzardapi2/wow/wow_api.py +0 -31
  63. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  64. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  65. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/.github/dependabot.yml +0 -0
  66. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/.github/workflows/README.md +0 -0
  67. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/.github/workflows/black-check.yml +0 -0
  68. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/CODE_OF_CONDUCT.md +0 -0
  69. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/LICENSE +0 -0
  70. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/SECURITY.md +0 -0
  71. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/diablo3/diablo3_community_api.py +0 -0
  72. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/hearthstone/hearthstone_game_data_api.py +0 -0
  73. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2/types.py +0 -0
  74. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2.egg-info/dependency_links.txt +0 -0
  75. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/blizzardapi2.egg-info/top_level.txt +0 -0
  76. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/docs/pull_request_template.md +0 -0
  77. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/setup.cfg +0 -0
  78. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/tests/__init__.py +0 -0
  79. {blizzardapi2-4.0.2 → blizzardapi2-5.1.0}/tests/test_types.py +0 -0
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env bash
2
+ # Prepares an Amp orb for blizzardapi2: a .venv with the package installed
3
+ # editable plus dev tools (pytest, ruff, black, isort), matching CI.
4
+ set -euo pipefail
5
+
6
+ cd "$(dirname "${BASH_SOURCE[0]}")/.."
7
+
8
+ step() {
9
+ local name="$1"
10
+ shift
11
+ local start=$SECONDS
12
+ echo "==> $name"
13
+ "$@"
14
+ echo " $name took $((SECONDS - start))s"
15
+ }
16
+
17
+ if ! command -v uv >/dev/null 2>&1; then
18
+ step "install uv" sh -c 'curl -LsSf --compressed https://astral.sh/uv/install.sh | sh'
19
+ export PATH="$HOME/.local/bin:$PATH"
20
+ fi
21
+
22
+ if [ ! -x .venv/bin/python ]; then
23
+ step "create .venv" uv venv
24
+ fi
25
+
26
+ # Same install as CI. On a warm snapshot uv only checks the installed set.
27
+ step "install dev dependencies" uv pip install -e ".[dev]"
@@ -0,0 +1,24 @@
1
+ name: PR Agent
2
+
3
+ # PR-Agent's version, model and settings live in the shared workflow in
4
+ # lostcol0ny/pr-agent-workflows; change them there, not here. This file only
5
+ # forwards events, because triggers, permissions and secrets cannot be shared.
6
+ # The shared workflow decides which of the forwarded events start a review.
7
+ on:
8
+ pull_request:
9
+ types: [opened, reopened, ready_for_review, synchronize]
10
+ issue_comment:
11
+ types: [created]
12
+
13
+ permissions:
14
+ contents: read
15
+
16
+ jobs:
17
+ pr_agent:
18
+ permissions:
19
+ contents: read
20
+ issues: write
21
+ pull-requests: write
22
+ uses: lostcol0ny/pr-agent-workflows/.github/workflows/pr_agent.yml@main
23
+ secrets:
24
+ OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
@@ -40,6 +40,9 @@ jobs:
40
40
  uv venv
41
41
  uv pip install -e ".[dev]"
42
42
 
43
+ - name: Lint with ruff
44
+ run: uv run ruff check .
45
+
43
46
  - name: Run tests
44
47
  run: uv run pytest tests/ -v
45
48
 
@@ -57,6 +60,7 @@ jobs:
57
60
  uses: actions/checkout@v4
58
61
  with:
59
62
  fetch-depth: 0
63
+ token: ${{ secrets.RELEASE_TOKEN }}
60
64
 
61
65
  - name: Configure Git
62
66
  run: |
@@ -83,7 +87,7 @@ jobs:
83
87
  - name: Run release script
84
88
  id: bump
85
89
  env:
86
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
90
+ GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
87
91
  run: |
88
92
  npx release-it --ci || {
89
93
  echo "release-it failed, creating GitHub release manually..."
@@ -136,6 +136,7 @@ dmypy.json
136
136
 
137
137
  # Claude Code
138
138
  .claude
139
+ .claude.local.md
139
140
 
140
141
  # Test project
141
142
  test_project/
@@ -150,4 +151,6 @@ poetry.lock
150
151
  *.patch
151
152
 
152
153
  # Node deps for release-it tooling
153
- node_modules/
154
+ node_modules/
155
+ # Amp orb portals
156
+ .amp/portals/*
@@ -1,4 +1,10 @@
1
1
  repos:
2
+ - repo: https://github.com/astral-sh/ruff-pre-commit
3
+ rev: v0.15.12
4
+ hooks:
5
+ - id: ruff
6
+ args: [--fix]
7
+
2
8
  - repo: https://github.com/psf/black
3
9
  rev: 26.3.1
4
10
  hooks:
@@ -0,0 +1,55 @@
1
+ // release-it config. JS instead of JSON so we can express a custom whatBump
2
+ // that suppresses noise releases (chore, ci, docs, style, test, refactor, build).
3
+ // Without this override, release-it falls back to a patch bump whenever there
4
+ // are any commits since the last tag — which is how v4.0.1 shipped from a
5
+ // chore-only PR.
6
+
7
+ const RELEASABLE_TYPES = new Set(["feat", "fix", "perf"]);
8
+
9
+ function whatBump(commits) {
10
+ let bump = null;
11
+
12
+ for (const commit of commits) {
13
+ const isBreaking =
14
+ (commit.notes || []).some((n) => /BREAKING/.test(n.title || "")) ||
15
+ / !$| !:|^[a-z]+!:/.test(commit.header || "");
16
+
17
+ if (isBreaking) {
18
+ return { level: 0, reason: "BREAKING CHANGE" }; // major
19
+ }
20
+
21
+ if (commit.type === "feat" && bump !== 1) {
22
+ bump = 1; // minor
23
+ } else if (RELEASABLE_TYPES.has(commit.type) && bump === null) {
24
+ bump = 2; // patch
25
+ }
26
+ }
27
+
28
+ // null = no release. release-it skips the bump/tag/publish chain.
29
+ return bump === null ? null : { level: bump };
30
+ }
31
+
32
+ module.exports = {
33
+ git: {
34
+ commitMessage: "chore: release v${version} [skip ci]",
35
+ tagName: "v${version}",
36
+ },
37
+ github: {
38
+ release: true,
39
+ releaseName: "Release v${version}",
40
+ },
41
+ npm: {
42
+ publish: false,
43
+ },
44
+ hooks: {
45
+ "after:bump": [
46
+ "sed -i 's/^version = \".*\"/version = \"${version}\"/' pyproject.toml",
47
+ ],
48
+ },
49
+ plugins: {
50
+ "@release-it/conventional-changelog": {
51
+ preset: "conventionalcommits",
52
+ whatBump,
53
+ },
54
+ },
55
+ };
@@ -46,15 +46,17 @@ All API classes inherit `BaseApi` (`api.py`). New endpoint methods are thin wrap
46
46
 
47
47
  `BaseApi._make_request` has a deliberate indirection: callers pass user OAuth tokens **inside `query_params` under the key `"access_token"`**. `_make_request` `.pop()`s that key and moves the value into the `Authorization: Bearer <token>` header. This keeps tokens out of URL query strings (visible in logs/proxies). Preserve this when adding OAuth-protected endpoints — see `battlenet/battlenet_oauth_api.py:get_user_info` for the canonical shape. Don't add a separate `access_token` keyword argument to `_make_request`; the pop-from-params pattern is the contract.
48
48
 
49
- Client-credentials tokens are managed automatically: `_ensure_valid_token` lazily fetches and caches them, with a 5-minute refresh buffer (`TOKEN_REFRESH_BUFFER`). On a 401 with a client-credentials token, `_make_request` refreshes and retries once. User-supplied OAuth tokens are never refreshed by the library.
49
+ Client-credentials tokens are managed automatically: `_client_token` lazily fetches them through a thread-safe `TokenManager` (`token_manager.py`), which caches one token per OAuth host (China, and global for every other region) with a 5-minute refresh buffer (`TOKEN_REFRESH_BUFFER`). On a 401 with a client-credentials token, `_make_request` replaces that token and retries once. User-supplied OAuth tokens are never refreshed by the library.
50
+
51
+ The default session (`endpoint.default_session`) retries 429 and 5xx responses with exponential backoff via urllib3 `Retry`. A caller-supplied `session` is used unchanged.
50
52
 
51
53
  ### Region URL routing
52
54
 
53
55
  `BaseApi.OAUTH_URLS` and `API_URLS` route China (`"cn"`) to `*.battlenet.com.cn` hosts, all other regions to `oauth.battle.net` and `{region}.api.blizzard.com`. Always use `_build_oauth_url` / `_build_api_url` rather than f-stringing URLs by hand.
54
56
 
55
- ### Independent token caches per sub-API
57
+ ### Shared token cache across sub-APIs
56
58
 
57
- Each game's facade instantiates its sub-APIs with `client_id`/`client_secret`, so `WowGameDataApi`, `WowProfileApi`, `Diablo3CommunityApi`, etc. each maintain their **own** `_session` and `_access_token`. There is no shared token cache across sub-APIs. This is fine for the current API surface but worth knowing if you're debugging unexpected token-fetch behavior.
59
+ Each facade passes its `session` and `token_manager` down to every sub-API it creates, so all sub-clients of one `BlizzardApi` share one HTTP session and one token cache. Pass both when adding a sub-API. Separate top-level clients get separate caches, since they may use different credentials.
58
60
 
59
61
  ### `Region` / `Locale` enums
60
62
 
@@ -42,7 +42,7 @@ The project uses several tools to maintain code quality:
42
42
 
43
43
  - **Black**: Code formatting
44
44
  - **isort**: Import sorting
45
- - **flake8**: Linting
45
+ - **ruff**: Linting
46
46
 
47
47
  ### Manual Formatting
48
48
 
@@ -56,7 +56,7 @@ black .
56
56
  isort .
57
57
 
58
58
  # Check linting
59
- flake8 .
59
+ ruff check .
60
60
  ```
61
61
 
62
62
  ## GitHub Workflows
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: blizzardapi2
3
- Version: 4.0.2
3
+ Version: 5.1.0
4
4
  Summary: A Python wrapper for Blizzard API
5
5
  Author-email: lostcol0ny <c098os0k@4wrd.cc>
6
6
  License-Expression: MIT
@@ -18,10 +18,10 @@ Requires-Dist: pytest<10.0.0,>=8.2.2; extra == "dev"
18
18
  Requires-Dist: pytest-mock<4.0.0,>=3.14.0; extra == "dev"
19
19
  Requires-Dist: pytest-asyncio<2.0.0,>=0.23.5; extra == "dev"
20
20
  Requires-Dist: black<27.0.0,>=26.3.1; extra == "dev"
21
- Requires-Dist: isort<9.0.0,>=8.0.1; extra == "dev"
21
+ Requires-Dist: isort<10.0.0,>=8.0.1; extra == "dev"
22
22
  Requires-Dist: ruff<1.0.0,>=0.3.0; extra == "dev"
23
23
  Requires-Dist: build<2.0.0,>=1.2.0; extra == "dev"
24
- Requires-Dist: twine<7.0.0,>=5.0.0; extra == "dev"
24
+ Requires-Dist: twine<8.0.0,>=5.0.0; extra == "dev"
25
25
  Dynamic: license-file
26
26
 
27
27
  # Blizzard API 2
@@ -75,28 +75,28 @@ Python (3.11+)
75
75
  **Basic Usage**
76
76
 
77
77
  ```python
78
- from blizzardapi2 import BlizzardApi
78
+ from blizzardapi2 import BlizzardApi, Region, Locale
79
79
 
80
80
  api_client = BlizzardApi("client_id", "client_secret")
81
81
 
82
82
  # Public API endpoint (uses automatic client credentials token)
83
83
  categories_index = api_client.wow.game_data.get_achievement_categories_index(
84
- "us", # region
85
- "en_US" # locale
84
+ region=Region.US,
85
+ locale=Locale.EN_US,
86
86
  )
87
87
 
88
88
  # Protected API endpoint (requires user OAuth token)
89
89
  summary = api_client.wow.profile.get_account_profile_summary(
90
- "us",
91
- "en_US",
92
- "user_access_token" # OAuth token from authorization code flow
90
+ "user_access_token", # OAuth token from authorization code flow
91
+ region=Region.US,
92
+ locale=Locale.EN_US,
93
93
  )
94
94
 
95
95
  # WoW Classic endpoint
96
96
  connected_realms_index = api_client.wow.game_data.get_connected_realms_index(
97
- "us",
98
- "en_US",
99
- is_classic=True
97
+ region=Region.US,
98
+ locale=Locale.EN_US,
99
+ is_classic=True,
100
100
  )
101
101
  ```
102
102
 
@@ -105,15 +105,21 @@ connected_realms_index = api_client.wow.game_data.get_connected_realms_index(
105
105
  The library automatically manages client credentials tokens for public endpoints:
106
106
 
107
107
  ```python
108
- from blizzardapi2 import BlizzardApi
108
+ from blizzardapi2 import BlizzardApi, Region, Locale
109
109
 
110
110
  api_client = BlizzardApi("client_id", "client_secret")
111
111
 
112
112
  # First call: library automatically fetches and caches a client credentials token
113
- realms = api_client.wow.game_data.get_realms_index("us", "en_US")
113
+ realms = api_client.wow.game_data.get_realms_index(
114
+ region=Region.US,
115
+ locale=Locale.EN_US,
116
+ )
114
117
 
115
118
  # Subsequent calls: library reuses the cached token
116
- achievements = api_client.wow.game_data.get_achievements_index("us", "en_US")
119
+ achievements = api_client.wow.game_data.get_achievements_index(
120
+ region=Region.US,
121
+ locale=Locale.EN_US,
122
+ )
117
123
 
118
124
  # When token expires: library automatically refreshes it
119
125
  # You don't need to manage tokens manually!
@@ -128,16 +134,19 @@ You can pass in a `client_id` and `client_secret` and use almost any endpoint ex
128
134
  2. Sends it via `Authorization: Bearer <token>` header
129
135
  3. Keeps tokens out of URL query strings
130
136
 
131
- Here is the list of endpoints, specified by Blizzard, that require an OAuth token:
132
-
133
- ```
134
- GET /oauth/userinfo
135
- GET /profile/user/wow
136
- GET /profile/user/wow/protected-character/{realm-id}-{character-id}
137
- GET /profile/user/wow/collections
138
- GET /profile/user/wow/collections/pets
139
- GET /profile/user/wow/collections/mounts
140
- ```
137
+ Here is the list of endpoints, and related API methods, that require an OAuth authorization code token:
138
+
139
+ | Resource path | API call |
140
+ | ------------- | -------- |
141
+ | /userinfo | `.battlenet.oauth.get_user_info(access_token)` |
142
+ | /profile/user/wow | `.wow.profile.get_account_profile_summary(access_token)` |
143
+ | /profile/user/wow/protected-character/{realm-id}-{character-id} | `.wow.profile.get_protected_character_profile_summary(access_token, realm_id, character_id)` |
144
+ | /profile/user/wow/collections | `.wow.profile.get_account_collections_index(access_token)` |
145
+ | /profile/user/wow/collections/heirlooms | `.wow.profile.get_account_heirlooms_collection_summary(access_token)` |
146
+ | /profile/user/wow/collections/mounts | `.wow.profile.get_account_mounts_collection_summary(access_token)` |
147
+ | /profile/user/wow/collections/pets | `.wow.profile.get_account_pets_collection_summary(access_token)` |
148
+ | /profile/user/wow/collections/toys | `.wow.profile.get_account_toys_collection_summary(access_token)` |
149
+ | /profile/user/wow/collections/transmogs | `.wow.profile.get_account_transmog_collection_summary(access_token)` |
141
150
 
142
151
  **Note:** For these protected endpoints, you must implement the OAuth authorization code flow in your application to obtain a user access token. The library does not handle the OAuth flow itself - it only accepts and uses the token you provide.
143
152
 
@@ -49,28 +49,28 @@ Python (3.11+)
49
49
  **Basic Usage**
50
50
 
51
51
  ```python
52
- from blizzardapi2 import BlizzardApi
52
+ from blizzardapi2 import BlizzardApi, Region, Locale
53
53
 
54
54
  api_client = BlizzardApi("client_id", "client_secret")
55
55
 
56
56
  # Public API endpoint (uses automatic client credentials token)
57
57
  categories_index = api_client.wow.game_data.get_achievement_categories_index(
58
- "us", # region
59
- "en_US" # locale
58
+ region=Region.US,
59
+ locale=Locale.EN_US,
60
60
  )
61
61
 
62
62
  # Protected API endpoint (requires user OAuth token)
63
63
  summary = api_client.wow.profile.get_account_profile_summary(
64
- "us",
65
- "en_US",
66
- "user_access_token" # OAuth token from authorization code flow
64
+ "user_access_token", # OAuth token from authorization code flow
65
+ region=Region.US,
66
+ locale=Locale.EN_US,
67
67
  )
68
68
 
69
69
  # WoW Classic endpoint
70
70
  connected_realms_index = api_client.wow.game_data.get_connected_realms_index(
71
- "us",
72
- "en_US",
73
- is_classic=True
71
+ region=Region.US,
72
+ locale=Locale.EN_US,
73
+ is_classic=True,
74
74
  )
75
75
  ```
76
76
 
@@ -79,15 +79,21 @@ connected_realms_index = api_client.wow.game_data.get_connected_realms_index(
79
79
  The library automatically manages client credentials tokens for public endpoints:
80
80
 
81
81
  ```python
82
- from blizzardapi2 import BlizzardApi
82
+ from blizzardapi2 import BlizzardApi, Region, Locale
83
83
 
84
84
  api_client = BlizzardApi("client_id", "client_secret")
85
85
 
86
86
  # First call: library automatically fetches and caches a client credentials token
87
- realms = api_client.wow.game_data.get_realms_index("us", "en_US")
87
+ realms = api_client.wow.game_data.get_realms_index(
88
+ region=Region.US,
89
+ locale=Locale.EN_US,
90
+ )
88
91
 
89
92
  # Subsequent calls: library reuses the cached token
90
- achievements = api_client.wow.game_data.get_achievements_index("us", "en_US")
93
+ achievements = api_client.wow.game_data.get_achievements_index(
94
+ region=Region.US,
95
+ locale=Locale.EN_US,
96
+ )
91
97
 
92
98
  # When token expires: library automatically refreshes it
93
99
  # You don't need to manage tokens manually!
@@ -102,16 +108,19 @@ You can pass in a `client_id` and `client_secret` and use almost any endpoint ex
102
108
  2. Sends it via `Authorization: Bearer <token>` header
103
109
  3. Keeps tokens out of URL query strings
104
110
 
105
- Here is the list of endpoints, specified by Blizzard, that require an OAuth token:
106
-
107
- ```
108
- GET /oauth/userinfo
109
- GET /profile/user/wow
110
- GET /profile/user/wow/protected-character/{realm-id}-{character-id}
111
- GET /profile/user/wow/collections
112
- GET /profile/user/wow/collections/pets
113
- GET /profile/user/wow/collections/mounts
114
- ```
111
+ Here is the list of endpoints, and related API methods, that require an OAuth authorization code token:
112
+
113
+ | Resource path | API call |
114
+ | ------------- | -------- |
115
+ | /userinfo | `.battlenet.oauth.get_user_info(access_token)` |
116
+ | /profile/user/wow | `.wow.profile.get_account_profile_summary(access_token)` |
117
+ | /profile/user/wow/protected-character/{realm-id}-{character-id} | `.wow.profile.get_protected_character_profile_summary(access_token, realm_id, character_id)` |
118
+ | /profile/user/wow/collections | `.wow.profile.get_account_collections_index(access_token)` |
119
+ | /profile/user/wow/collections/heirlooms | `.wow.profile.get_account_heirlooms_collection_summary(access_token)` |
120
+ | /profile/user/wow/collections/mounts | `.wow.profile.get_account_mounts_collection_summary(access_token)` |
121
+ | /profile/user/wow/collections/pets | `.wow.profile.get_account_pets_collection_summary(access_token)` |
122
+ | /profile/user/wow/collections/toys | `.wow.profile.get_account_toys_collection_summary(access_token)` |
123
+ | /profile/user/wow/collections/transmogs | `.wow.profile.get_account_transmog_collection_summary(access_token)` |
115
124
 
116
125
  **Note:** For these protected endpoints, you must implement the OAuth authorization code flow in your application to obtain a user access token. The library does not handle the OAuth flow itself - it only accepts and uses the token you provide.
117
126
 
@@ -3,3 +3,4 @@
3
3
  from requests.exceptions import * # noqa
4
4
 
5
5
  from .blizzard_api import BlizzardApi # noqa
6
+ from .types import Locale, Region # noqa
@@ -1,6 +1,6 @@
1
1
  """api.py file."""
2
2
 
3
- from datetime import UTC, datetime, timedelta
3
+ from datetime import timedelta
4
4
  from typing import Any, Optional
5
5
 
6
6
  import requests
@@ -35,47 +35,60 @@ class BaseApi(ApiEndpoint):
35
35
  DEFAULT_GET_TIMEOUT = 30.0
36
36
  DEFAULT_POST_TIMEOUT = 10.0
37
37
 
38
- def extend_endpoint(self) -> None:
39
- self._access_token: Optional[str] = None
40
- self._token_expires_at: Optional[datetime] = None
41
- self._session = requests.Session()
42
-
43
- def _is_token_expired(self) -> bool:
44
- """Check if the token is expiring within the refresh buffer window."""
45
- if self._token_expires_at is None:
46
- return True
47
- return datetime.now(UTC) >= self._token_expires_at - self.TOKEN_REFRESH_BUFFER
48
-
49
- def _get_client_token(self, region: str) -> dict[str, Any]:
38
+ def _get_client_token(self, region: Region | str) -> dict[str, Any]:
50
39
  """Fetch an access token using client credentials flow.
51
40
 
52
41
  Args:
53
- region: The region to query (e.g., us, eu, kr, tw, cn). Defaults to None, in which case the default region provided at instantiation is used.
42
+ region: The region whose OAuth host issues the token (e.g., us, cn).
54
43
 
55
44
  Returns:
56
45
  The token response from the API.
57
46
  """
58
47
  url = self._build_oauth_url("/oauth/token", region)
59
- response = self._session.post(
48
+ response = self.session.post(
60
49
  url,
61
50
  params={"grant_type": "client_credentials"},
62
51
  auth=(self.client_id, self._client_secret),
63
52
  timeout=self.DEFAULT_POST_TIMEOUT,
64
53
  )
65
54
  response.raise_for_status()
66
- token_data = response.json()
55
+ return response.json()
67
56
 
68
- # Store token and calculate expiration
69
- self._access_token = token_data["access_token"]
70
- expires_in = token_data.get("expires_in", 86400) # Default 24 hours
71
- self._token_expires_at = datetime.now(UTC) + timedelta(seconds=expires_in)
57
+ def _client_token(
58
+ self, region: Region | str, stale_token: Optional[str] = None
59
+ ) -> str:
60
+ """Return a valid client credentials token for the region's OAuth host.
72
61
 
73
- return token_data
62
+ Tokens are cached in the shared ``token_manager``: one for China and
63
+ one for every other region.
74
64
 
75
- def _ensure_valid_token(self, region: str) -> None:
76
- """Ensure we have a valid client credentials token."""
77
- if self._access_token is None or self._is_token_expired():
78
- self._get_client_token(region)
65
+ Args:
66
+ region: The region to query (e.g., us, eu, kr, tw, cn).
67
+ stale_token: A token the API rejected with 401, to replace.
68
+
69
+ Returns:
70
+ The access token.
71
+ """
72
+ return self.token_manager.get_token(
73
+ self._build_oauth_url("/oauth/token", region),
74
+ lambda: self._get_client_token(region),
75
+ self.TOKEN_REFRESH_BUFFER,
76
+ stale_token=stale_token,
77
+ )
78
+
79
+ def _resolve_region(self, region: OptionalRegion) -> Region:
80
+ """Return the given region, or the default region set at instantiation.
81
+
82
+ Raises:
83
+ ValueError: If neither is set, or the region is not a valid Region.
84
+ """
85
+ resolved = region or self.region
86
+ if resolved is None:
87
+ raise ValueError(
88
+ "No Region given: pass region=... or set a default region when "
89
+ "creating the client, e.g. BlizzardApi(id, secret, region=Region.US)"
90
+ )
91
+ return Region(resolved)
79
92
 
80
93
  def _build_oauth_url(self, resource: str, region: Region | str) -> str:
81
94
  """Build URL for OAuth endpoints.
@@ -105,6 +118,15 @@ class BaseApi(ApiEndpoint):
105
118
  )
106
119
  return f"{base_url}{resource}"
107
120
 
121
+ def _get(self, url: str, params: dict[str, Any], token: str) -> requests.Response:
122
+ """Send an authenticated GET request."""
123
+ return self.session.get(
124
+ url,
125
+ params=params,
126
+ headers={"Authorization": f"Bearer {token}"},
127
+ timeout=self.DEFAULT_GET_TIMEOUT,
128
+ )
129
+
108
130
  def _make_request(
109
131
  self,
110
132
  url: str,
@@ -127,33 +149,16 @@ class BaseApi(ApiEndpoint):
127
149
  # Check if user provided their own access token
128
150
  user_token = params.pop("access_token", None)
129
151
 
130
- # Determine which token to use
131
- if user_token:
132
- # Use user-provided token (for OAuth user endpoints)
133
- token = user_token
134
- else:
135
- # Ensure client credentials token is valid
136
- self._ensure_valid_token(region)
137
- token = self._access_token
138
-
139
- # Make the request
140
- response = self._session.get(
141
- url,
142
- params=params,
143
- headers={"Authorization": f"Bearer {token}"},
144
- timeout=self.DEFAULT_GET_TIMEOUT,
145
- )
152
+ # Use the user-provided token (for OAuth user endpoints) or a client
153
+ # credentials token
154
+ token = user_token or self._client_token(region)
155
+ response = self._get(url, params, token)
146
156
 
147
157
  # Handle 401 errors for client credentials (not user tokens)
148
158
  if response.status_code == 401 and not user_token:
149
159
  # Token might have expired, refresh and retry
150
- self._get_client_token(region)
151
- response = self._session.get(
152
- url,
153
- params=params,
154
- headers={"Authorization": f"Bearer {self._access_token}"},
155
- timeout=self.DEFAULT_GET_TIMEOUT,
156
- )
160
+ token = self._client_token(region, stale_token=token)
161
+ response = self._get(url, params, token)
157
162
 
158
163
  response.raise_for_status()
159
164
  return response.json()
@@ -174,7 +179,7 @@ class BaseApi(ApiEndpoint):
174
179
  Returns:
175
180
  The API response as a dictionary.
176
181
  """
177
- _region = Region(region or self.region)
182
+ _region = self._resolve_region(region)
178
183
  url = self._build_api_url(resource, _region)
179
184
  return self._make_request(url, _region, query_params)
180
185
 
@@ -194,7 +199,7 @@ class BaseApi(ApiEndpoint):
194
199
  Returns:
195
200
  The API response as a dictionary.
196
201
  """
197
- _region = Region(region or self.region)
202
+ _region = self._resolve_region(region)
198
203
  url = self._build_oauth_url(resource, _region)
199
204
  return self._make_request(url, _region, query_params)
200
205
 
@@ -0,0 +1,5 @@
1
+ """__init__.py file."""
2
+
3
+ from ..types import Locale, Region # noqa
4
+ from .battlenet_api import BattlenetApi # noqa
5
+ from .battlenet_oauth_api import BattlenetOAuthApi # noqa
@@ -11,9 +11,16 @@ class BattlenetApi(ApiEndpoint):
11
11
  client_id (str): A string client id supplied by Blizzard.
12
12
  client_secret (str): A string client secret supplied by Blizzard.
13
13
  region (Region, optional): Default region to use for requests.
14
+ session (requests.Session, optional): A default session to use for requests.
14
15
  oauth (BattlenetOAuthApi): An instance of the BattlenetOAuthApi class for accessing OAuth endpoints.
15
16
  """
16
17
 
17
18
  def extend_endpoint(self) -> None:
18
19
  """Init BattlenetApi."""
19
- self.oauth = BattlenetOAuthApi(self.client_id, self.client_secret, self.region)
20
+ self.oauth = BattlenetOAuthApi(
21
+ self.client_id,
22
+ self.client_secret,
23
+ region=self.region,
24
+ session=self.session,
25
+ token_manager=self.token_manager,
26
+ )
@@ -38,7 +38,7 @@ class BattlenetOAuthApi(BaseApi):
38
38
  requests.HTTPError: If the API request fails (raised via
39
39
  ``response.raise_for_status()`` in ``BaseApi._make_request``).
40
40
  """
41
- resource = "/oauth/userinfo"
41
+ resource = "/userinfo"
42
42
  query_params = {
43
43
  "access_token": access_token,
44
44
  }