API Reference¶
Full reference for all public modules in the cocapi package. Select a module from the navigation to view its documentation.
cocapi
¶
Clash of Clans API Wrapper - cocapi v4.0.0
A Python wrapper for the official Clash of Clans API with enhanced features: - Async and sync support - Request caching with TTL - Automatic retries with exponential backoff - Request metrics and monitoring - Middleware system for request/response processing - Dynamic Pydantic model generation - Custom endpoint support for future API changes - Configurable base URL with safety warnings
Basic Usage
from cocapi import CocApi
api = CocApi("your_api_token") clan = api.clan_tag("#CLAN_TAG")
Advanced Usage
from cocapi import CocApi, ApiConfig
config = ApiConfig( enable_caching=True, cache_ttl=600, max_retries=3, enable_metrics=True )
api = CocApi("your_token", config=config)
Async Usage
from cocapi import CocApi, ApiConfig
async def get_clan_info(): config = ApiConfig(enable_rate_limiting=True) async with CocApi("token", config=config) as api: clan = await api.clan_tag("#CLAN_TAG") return clan
AsyncCocApiCore
¶
AsyncCocApiCore(token: str, config: ApiConfig)
Core async functionality for CocApi
Initialize async core
| PARAMETER | DESCRIPTION |
|---|---|
token
|
API token
TYPE:
|
config
|
Configuration object
TYPE:
|
Source code in cocapi/async_client.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
__aenter__
async
¶
__aenter__() -> AsyncCocApiCore
Async context manager entry
Source code in cocapi/async_client.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 | |
__aexit__
async
¶
__aexit__(exc_type: Any, exc_val: Any, exc_tb: Any) -> None
Async context manager exit
Source code in cocapi/async_client.py
114 115 116 117 118 119 | |
set_key_manager_state
¶
set_key_manager_state(
email: str,
password: str,
key_name: str,
key_count: int,
auto_refresh: bool,
persist_keys: bool = False,
key_storage_path: str | None = None,
) -> None
Store key manager credentials for auto-refresh on 403.
Source code in cocapi/async_client.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
make_request
async
¶
make_request(
endpoint: str,
params: dict[str, Any] | None = None,
use_dynamic_model: bool = False,
_refresh_attempted: bool = False,
) -> dict[str, Any]
Make an async API request
| PARAMETER | DESCRIPTION |
|---|---|
endpoint
|
API endpoint path
TYPE:
|
params
|
Request parameters
TYPE:
|
use_dynamic_model
|
Whether to create dynamic Pydantic models
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
API response as dictionary |
Source code in cocapi/async_client.py
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 | |
make_post_request
async
¶
make_post_request(
endpoint: str,
json_body: dict[str, Any],
params: dict[str, Any] | None = None,
use_dynamic_model: bool = False,
_refresh_attempted: bool = False,
) -> dict[str, Any]
Make an async POST API request
| PARAMETER | DESCRIPTION |
|---|---|
endpoint
|
API endpoint path
TYPE:
|
json_body
|
JSON body to send with the POST request
TYPE:
|
params
|
Optional query parameters
TYPE:
|
use_dynamic_model
|
Whether to create dynamic Pydantic models
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
API response as dictionary |
Source code in cocapi/async_client.py
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 | |
test_connection
async
¶
test_connection() -> dict[str, Any]
Test API connection
Source code in cocapi/async_client.py
599 600 601 602 603 604 605 606 607 608 609 610 611 | |
AsyncRateLimiter
¶
AsyncRateLimiter(rate: float, burst: int)
Simple async rate limiter using token bucket algorithm
Initialize rate limiter
| PARAMETER | DESCRIPTION |
|---|---|
rate
|
Requests per second
TYPE:
|
burst
|
Maximum burst requests
TYPE:
|
Source code in cocapi/async_client.py
23 24 25 26 27 28 29 30 31 32 33 34 35 | |
acquire
async
¶
acquire() -> None
Acquire permission to make a request
Source code in cocapi/async_client.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
CacheManager
¶
CacheManager(default_ttl: int = 300)
Manages response caching with TTL support
Initialize cache manager
| PARAMETER | DESCRIPTION |
|---|---|
default_ttl
|
Default time-to-live in seconds (5 minutes)
TYPE:
|
Source code in cocapi/cache.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
enable
¶
enable() -> None
Enable caching
Source code in cocapi/cache.py
32 33 34 | |
disable
¶
disable() -> None
Disable caching
Source code in cocapi/cache.py
36 37 38 | |
is_enabled
¶
is_enabled() -> bool
Check if caching is enabled
Source code in cocapi/cache.py
40 41 42 | |
get
¶
get(
url: str, params: dict[str, Any] | None = None
) -> dict[str, Any] | None
Get cached response if available and not expired
| PARAMETER | DESCRIPTION |
|---|---|
url
|
Request URL
TYPE:
|
params
|
Request parameters
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | None
|
Cached response data or None if not found/expired |
Source code in cocapi/cache.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
set
¶
set(
url: str,
params: dict[str, Any] | None,
data: dict[str, Any],
ttl: int | None = None,
) -> None
Cache response data
| PARAMETER | DESCRIPTION |
|---|---|
url
|
Request URL
TYPE:
|
params
|
Request parameters
TYPE:
|
data
|
Response data to cache
TYPE:
|
ttl
|
Time-to-live in seconds (uses default if not specified)
TYPE:
|
Source code in cocapi/cache.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | |
invalidate
¶
invalidate(
url: str, params: dict[str, Any] | None = None
) -> bool
Invalidate specific cached entry
| PARAMETER | DESCRIPTION |
|---|---|
url
|
Request URL
TYPE:
|
params
|
Request parameters
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if entry was found and removed, False otherwise |
Source code in cocapi/cache.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
clear
¶
clear() -> int
Clear all cached entries
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of entries cleared |
Source code in cocapi/cache.py
129 130 131 132 133 134 135 136 137 138 139 | |
cleanup_expired
¶
cleanup_expired() -> int
Remove expired entries
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of expired entries removed |
Source code in cocapi/cache.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |
get_stats
¶
get_stats() -> dict[str, Any]
Get cache statistics
Source code in cocapi/cache.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
get_cache_info
¶
get_cache_info() -> dict[str, Any]
Get detailed cache information
Source code in cocapi/cache.py
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
set_default_ttl
¶
set_default_ttl(ttl: int) -> None
Set default TTL for new cache entries
Source code in cocapi/cache.py
211 212 213 | |
get_entry_info
¶
get_entry_info(
url: str, params: dict[str, Any] | None = None
) -> dict[str, Any] | None
Get information about a specific cache entry
Source code in cocapi/cache.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
extend_ttl
¶
extend_ttl(
url: str,
params: dict[str, Any] | None = None,
additional_seconds: int = 300,
) -> bool
Extend TTL for a specific cache entry
| PARAMETER | DESCRIPTION |
|---|---|
url
|
Request URL
TYPE:
|
params
|
Request parameters
TYPE:
|
additional_seconds
|
Seconds to add to current TTL
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if entry was found and updated, False otherwise |
Source code in cocapi/cache.py
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
touch
¶
touch(
url: str, params: dict[str, Any] | None = None
) -> bool
Reset timestamp for cache entry (extends its life without changing TTL)
| PARAMETER | DESCRIPTION |
|---|---|
url
|
Request URL
TYPE:
|
params
|
Request parameters
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if entry was found and touched, False otherwise |
Source code in cocapi/cache.py
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | |
CocApi
¶
CocApi(
token: str,
timeout: int = 20,
status_code: bool = False,
config: ApiConfig | None = None,
async_mode: bool = False,
)
Bases: ApiMethods
Clash of Clans API Wrapper with enhanced v3.0.0 features
Provides both sync and async interfaces with caching, metrics, middleware, and dynamic model generation capabilities.
Initialize CocApi with enhanced features
| PARAMETER | DESCRIPTION |
|---|---|
token
|
API token from developer.clashofclans.com
TYPE:
|
timeout
|
Request timeout in seconds (backward compatibility)
TYPE:
|
status_code
|
Include status code in responses (backward compatibility)
TYPE:
|
config
|
Optional ApiConfig for advanced settings
TYPE:
|
async_mode
|
Enable async mode (default: False for backward compatibility)
TYPE:
|
Source code in cocapi/client.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | |
from_credentials
classmethod
¶
from_credentials(
email: str,
password: str,
timeout: int = 20,
status_code: bool = False,
config: ApiConfig | None = None,
) -> CocApi
Create a CocApi instance using SuperCell developer portal credentials.
Instead of providing a raw API token, provide your developer portal email and password. Keys are automatically created and managed based on your current public IP.
| PARAMETER | DESCRIPTION |
|---|---|
email
|
SuperCell developer portal email
TYPE:
|
password
|
SuperCell developer portal password
TYPE:
|
timeout
|
Request timeout in seconds
TYPE:
|
status_code
|
Include status code in responses
TYPE:
|
config
|
Optional ApiConfig for advanced settings
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CocApi
|
Configured CocApi instance with a managed API token |
Example::
api = CocApi.from_credentials("email@example.com", "password")
clan = api.clan_tag("#CLAN_TAG")
Source code in cocapi/client.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
__aenter__
async
¶
__aenter__() -> CocApi
Async context manager entry - enables async mode automatically
Source code in cocapi/client.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | |
__aexit__
async
¶
__aexit__(exc_type: Any, exc_val: Any, exc_tb: Any) -> None
Async context manager exit
Source code in cocapi/client.py
228 229 230 231 232 | |
test
¶
test() -> dict[str, Any]
Test API connection
Source code in cocapi/client.py
510 511 512 513 514 515 516 517 518 519 520 521 522 | |
paginate
¶
paginate(
method: Callable[..., Any], *args: Any, limit: int = 100
) -> Any
Auto-paginate through all results from a list endpoint.
Yields individual items from each page, automatically following
the after cursor until all pages are exhausted.
| PARAMETER | DESCRIPTION |
|---|---|
method
|
An API method that returns paginated results
(e.g.
TYPE:
|
*args
|
Positional arguments for the method excluding the
TYPE:
|
limit
|
Items per page (default 100).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
Generator (sync) or async generator (async) of individual items. |
Example::
for member in api.paginate(api.clan_members, "#TAG"):
print(member["name"])
Source code in cocapi/client.py
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 | |
batch
¶
batch(
method: Callable[..., Any],
args_list: list[Any],
max_concurrent: int | None = None,
) -> list[dict[str, Any]] | Awaitable[list[dict[str, Any]]]
Fetch multiple resources in one call.
| PARAMETER | DESCRIPTION |
|---|---|
method
|
An API method (e.g.
TYPE:
|
args_list
|
List of arguments — each element is passed to method. Use tuples for methods that take multiple positional args.
TYPE:
|
max_concurrent
|
Limit concurrent requests in async mode (ignored in sync mode).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[dict[str, Any]] | Awaitable[list[dict[str, Any]]]
|
List of response dicts (sync) or awaitable list (async). |
list[dict[str, Any]] | Awaitable[list[dict[str, Any]]]
|
Failed calls return their error dict in-place. |
Example::
results = api.batch(api.players, ["#TAG1", "#TAG2", "#TAG3"])
Source code in cocapi/client.py
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 | |
custom_endpoint
¶
custom_endpoint(
endpoint_path: str,
params: dict[str, Any] | None = None,
use_dynamic_model: bool = False,
) -> dict[str, Any] | Awaitable[dict[str, Any]]
Call a custom API endpoint (future-proofing for new SuperCell endpoints)
| PARAMETER | DESCRIPTION |
|---|---|
endpoint_path
|
The endpoint path (e.g., "/clans/new-feature")
TYPE:
|
params
|
Optional query parameters
TYPE:
|
use_dynamic_model
|
Whether to generate dynamic Pydantic models
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Awaitable[dict[str, Any]]
|
API response as dict or Pydantic model |
Source code in cocapi/client.py
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 | |
set_base_url
¶
set_base_url(
new_base_url: str, force: bool = False
) -> None
Change the base API URL with safety warnings
| PARAMETER | DESCRIPTION |
|---|---|
new_base_url
|
New base URL to use
TYPE:
|
force
|
Skip safety warnings (use with caution)
TYPE:
|
Source code in cocapi/client.py
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 | |
get_base_url
¶
get_base_url() -> str
Get current base URL
Source code in cocapi/client.py
964 965 966 | |
reset_base_url
¶
reset_base_url() -> None
Reset to official SuperCell API URL
Source code in cocapi/client.py
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 | |
add_request_middleware
¶
add_request_middleware(
middleware: Callable[
[str, dict[str, str], dict[str, Any]],
tuple[str, dict[str, str], dict[str, Any]],
],
) -> None
Add request middleware - delegates to middleware manager
Source code in cocapi/client.py
987 988 989 990 991 992 993 994 995 | |
add_response_middleware
¶
add_response_middleware(
middleware: Callable[[dict[str, Any]], dict[str, Any]],
) -> None
Add response middleware - delegates to middleware manager
Source code in cocapi/client.py
997 998 999 1000 1001 | |
get_metrics
¶
get_metrics() -> dict[str, Any]
Get API metrics summary
Source code in cocapi/client.py
1004 1005 1006 | |
clear_metrics
¶
clear_metrics() -> None
Clear stored metrics
Source code in cocapi/client.py
1008 1009 1010 | |
clear_cache
¶
clear_cache() -> int
Clear API response cache
Source code in cocapi/client.py
1013 1014 1015 | |
get_cache_stats
¶
get_cache_stats() -> dict[str, Any]
Get cache statistics
Source code in cocapi/client.py
1017 1018 1019 | |
ApiConfig
dataclass
¶
ApiConfig(
base_url: str = "https://api.clashofclans.com/v1",
timeout: int = 20,
max_retries: int = 3,
retry_delay: float = 1.0,
cache_ttl: int = 300,
enable_caching: bool = True,
enable_rate_limiting: bool = True,
use_pydantic_models: bool = False,
requests_per_second: float = 10.0,
burst_limit: int = 20,
enable_metrics: bool = False,
metrics_window_size: int = 1000,
enable_keepalive: bool = True,
max_connections: int = 10,
max_keepalive_connections: int = 5,
key_name: str = "cocapi_auto",
key_count: int = 1,
key_description: str = "Auto-generated by cocapi KeyManager",
auto_refresh_keys: bool = True,
persist_keys: bool = False,
key_storage_path: str | None = None,
)
Configuration class for CocApi
CacheEntry
dataclass
¶
CacheEntry(data: dict, timestamp: float, ttl: int)
Cache entry with TTL support
is_expired
¶
is_expired(current_time: float) -> bool
Check if cache entry is expired
Source code in cocapi/config.py
53 54 55 | |
RequestMetric
dataclass
¶
RequestMetric(
endpoint: str,
method: str,
status_code: int,
response_time: float,
timestamp: float,
cache_hit: bool,
error_type: str | None = None,
)
Metrics for a single API request
AsyncKeyManager
¶
AsyncKeyManager(
email: str,
password: str,
key_name: str = "cocapi_auto",
key_count: int = 1,
key_description: str = "Auto-generated by cocapi KeyManager",
key_scopes: str = "clash",
persist_keys: bool = False,
key_storage_path: str | None = None,
)
Async key manager for the SuperCell developer portal.
Same functionality as SyncKeyManager but using httpx.AsyncClient.
Usage::
async with AsyncKeyManager("email", "password") as km:
tokens = await km.manage_keys()
Source code in cocapi/key_manager.py
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | |
close
async
¶
close() -> None
Close the underlying async HTTP client.
Source code in cocapi/key_manager.py
597 598 599 600 601 | |
manage_keys
async
¶
manage_keys() -> list[str]
Main orchestration: ensure we have valid keys for the current IP. Same logic as SyncKeyManager.manage_keys() but async.
Source code in cocapi/key_manager.py
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 | |
refresh_keys
async
¶
refresh_keys() -> list[str]
Re-detect IP and re-initialize keys.
Source code in cocapi/key_manager.py
818 819 820 821 822 823 824 825 | |
InvalidCredentials
¶
Bases: KeyManagerError
Raised when email/password login fails.
KeyManagerError
¶
Bases: Exception
Base exception for key manager errors.
SyncKeyManager
¶
SyncKeyManager(
email: str,
password: str,
key_name: str = "cocapi_auto",
key_count: int = 1,
key_description: str = "Auto-generated by cocapi KeyManager",
key_scopes: str = "clash",
persist_keys: bool = False,
key_storage_path: str | None = None,
)
Synchronous key manager for the SuperCell developer portal.
Handles login, IP detection, and API key lifecycle management using httpx.Client with cookie persistence.
Usage::
with SyncKeyManager("email", "password") as km:
tokens = km.manage_keys()
# Use tokens[0] with CocApi
Or via CocApi integration::
api = CocApi.from_credentials("email@example.com", "password")
Source code in cocapi/key_manager.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
close
¶
close() -> None
Close the underlying HTTP client.
Source code in cocapi/key_manager.py
292 293 294 | |
manage_keys
¶
manage_keys() -> list[str]
Main orchestration: ensure we have valid keys for the current IP.
If persist_keys is enabled, checks the local cache first. When the cached IP matches the current IP, returns cached tokens immediately without contacting the developer portal.
- (Optional) Check local cache
- Login to developer portal
- Detect current public IP
- List existing keys
- Revoke stale keys (wrong IP), keep valid ones
- Create new keys if needed
- (Optional) Save tokens to local cache
- Return list of usable API token strings
Source code in cocapi/key_manager.py
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 | |
refresh_keys
¶
refresh_keys() -> list[str]
Re-detect IP and re-initialize keys.
Call this when the API returns accessDenied.invalidIp.
Source code in cocapi/key_manager.py
533 534 535 536 537 538 539 540 541 542 543 544 | |
MetricsTracker
¶
MetricsTracker(max_metrics: int = 1000)
Tracks API request metrics and statistics
Initialize metrics tracker
| PARAMETER | DESCRIPTION |
|---|---|
max_metrics
|
Maximum number of metrics to store (oldest are removed)
TYPE:
|
Source code in cocapi/metrics.py
16 17 18 19 20 21 22 23 24 25 | |
enable
¶
enable() -> None
Enable metrics tracking
Source code in cocapi/metrics.py
27 28 29 | |
disable
¶
disable() -> None
Disable metrics tracking
Source code in cocapi/metrics.py
31 32 33 | |
is_enabled
¶
is_enabled() -> bool
Check if metrics tracking is enabled
Source code in cocapi/metrics.py
35 36 37 | |
record_request
¶
record_request(
endpoint: str,
method: str,
status_code: int,
response_time: float,
cache_hit: bool,
error_type: str | None = None,
) -> None
Record metrics for a request if metrics are enabled
Source code in cocapi/metrics.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | |
get_metrics_summary
¶
get_metrics_summary() -> dict[str, Any]
Get comprehensive metrics summary
Source code in cocapi/metrics.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
get_endpoint_metrics
¶
get_endpoint_metrics(endpoint: str) -> dict[str, Any]
Get metrics for a specific endpoint
Source code in cocapi/metrics.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
get_recent_errors
¶
get_recent_errors(limit: int = 10) -> list[dict[str, Any]]
Get recent error requests
Source code in cocapi/metrics.py
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
clear_metrics
¶
clear_metrics() -> None
Clear all stored metrics
Source code in cocapi/metrics.py
189 190 191 | |
export_metrics_csv
¶
export_metrics_csv() -> str
Export metrics as CSV string
Source code in cocapi/metrics.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
get_performance_insights
¶
get_performance_insights() -> dict[str, Any]
Get performance insights and recommendations
Source code in cocapi/metrics.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | |
MiddlewareManager
¶
MiddlewareManager()
Manages request and response middleware
Source code in cocapi/middleware.py
13 14 15 16 17 18 19 20 | |
add_request_middleware
¶
add_request_middleware(
middleware: Callable[
[str, dict[str, str], dict[str, Any]],
tuple[str, dict[str, str], dict[str, Any]],
],
) -> None
Add middleware function to process requests before they're sent.
| PARAMETER | DESCRIPTION |
|---|---|
middleware
|
Function that takes (url, headers, params) and returns modified versions
TYPE:
|
Examples:
def add_custom_header(url, headers, params): headers = headers.copy() headers['X-Custom'] = 'MyApp' return url, headers, params
manager.add_request_middleware(add_custom_header)
Source code in cocapi/middleware.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
add_response_middleware
¶
add_response_middleware(
middleware: Callable[[dict[str, Any]], dict[str, Any]],
) -> None
Add middleware function to process responses after they're received.
| PARAMETER | DESCRIPTION |
|---|---|
middleware
|
Function that takes response dict and returns modified version
TYPE:
|
Examples:
def add_timestamp(response): response['_processed_at'] = time.time() return response
manager.add_response_middleware(add_timestamp)
Source code in cocapi/middleware.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
apply_request_middleware
¶
apply_request_middleware(
url: str,
headers: dict[str, str],
params: dict[str, Any],
) -> tuple[str, dict[str, str], dict[str, Any]]
Apply all request middleware in order
Source code in cocapi/middleware.py
63 64 65 66 67 68 69 70 71 72 | |
apply_response_middleware
¶
apply_response_middleware(
response: dict[str, Any],
) -> dict[str, Any]
Apply all response middleware in order
Source code in cocapi/middleware.py
74 75 76 77 78 79 80 81 | |
clear_request_middleware
¶
clear_request_middleware() -> None
Clear all request middleware
Source code in cocapi/middleware.py
83 84 85 | |
clear_response_middleware
¶
clear_response_middleware() -> None
Clear all response middleware
Source code in cocapi/middleware.py
87 88 89 | |
clear_all_middleware
¶
clear_all_middleware() -> None
Clear all middleware
Source code in cocapi/middleware.py
91 92 93 94 | |
get_middleware_info
¶
get_middleware_info() -> dict[str, Any]
Get information about registered middleware
Source code in cocapi/middleware.py
96 97 98 99 100 101 102 103 104 105 106 107 | |
Achievement
¶
Bases: BaseModel
A player achievement with progress and star count.
BadgeUrls
¶
Bases: BaseModel
Clan badge image URLs in multiple sizes.
BuilderBaseLeague
¶
Bases: BaseModel
Builder Base league ranking.
CapitalLeague
¶
Bases: BaseModel
Clan Capital league ranking.
ChatLanguage
¶
Bases: BaseModel
A clan's configured chat language.
Clan
¶
Bases: BaseModel
Full clan profile from the /clans/{tag} endpoint.
ClanBuilderBaseRankingEntry
¶
Bases: BaseModel
A clan's entry in the Builder Base rankings leaderboard.
ClanCapital
¶
Bases: BaseModel
Clan Capital data including hall level and districts.
ClanCapitalRaidSeason
¶
Bases: BaseModel
A Clan Capital raid season with attack/defense logs and rewards.
ClanCapitalRankingEntry
¶
Bases: BaseModel
A clan's entry in the Clan Capital rankings leaderboard.
ClanMember
¶
Bases: BaseModel
A member entry within a clan's member list.
ClanRankingEntry
¶
Bases: BaseModel
A clan's entry in the trophy rankings leaderboard.
ClanSearchEntry
¶
Bases: BaseModel
Clan entry returned from the search endpoint (no memberList).
ClanWar
¶
Bases: BaseModel
Current or past clan war from the /clans/{tag}/currentwar endpoint.
ClanWarLeagueClan
¶
Bases: BaseModel
A clan participating in a Clan War League group.
ClanWarLeagueGroup
¶
Bases: BaseModel
Full Clan War League group with clans and rounds.
ClanWarLeagueMember
¶
Bases: BaseModel
A member in a Clan War League group.
ClanWarLeagueRound
¶
Bases: BaseModel
A round within a Clan War League season containing war tags.
ClanWarLogEntry
¶
Bases: BaseModel
A single entry in a clan's war log.
GoldPassSeason
¶
Bases: BaseModel
Current Gold Pass season start and end times.
Hero
¶
Bases: BaseModel
A hero unit (e.g. Barbarian King, Archer Queen).
HeroEquipment
¶
Bases: BaseModel
Equipment item that can be assigned to a hero.
IconUrls
¶
Bases: BaseModel
Icon image URLs for leagues, labels, and other entities.
Label
¶
Bases: BaseModel
A label that can be assigned to clans or players.
League
¶
Bases: BaseModel
A player's trophy league (e.g. Legend League, Titan I).
LeagueSeason
¶
Bases: BaseModel
A league season identifier (e.g. 2026-02).
LeagueTier
¶
Bases: BaseModel
A tier within a league (sub-division).
Location
¶
Bases: BaseModel
A geographic location (country or region) used for rankings.
Paging
¶
Bases: BaseModel
Paging metadata returned with paginated list responses.
Player
¶
Bases: BaseModel
Full player profile from the /players/{tag} endpoint.
PlayerBuilderBaseRankingEntry
¶
Bases: BaseModel
A player's entry in the Builder Base rankings leaderboard.
PlayerClan
¶
Bases: BaseModel
Compact clan info embedded in player responses.
PlayerHouse
¶
Bases: BaseModel
Player house decoration data.
PlayerRankingEntry
¶
Bases: BaseModel
A player's entry in the trophy rankings leaderboard.
Spell
¶
Bases: BaseModel
A spell in a player's spell factory.
Troop
¶
Bases: BaseModel
A troop in a player's army (home or builder village).
VerifyTokenResponse
¶
Bases: BaseModel
Response from the player token verification endpoint.
WarAttack
¶
Bases: BaseModel
A single attack in a clan war.
WarClan
¶
Bases: BaseModel
A clan's war data including members and attack summary.
WarLeague
¶
Bases: BaseModel
Clan War League tier (e.g. Champion I, Master II).
WarMember
¶
Bases: BaseModel
A clan member participating in a war.
add_debug_logging_middleware
¶
add_debug_logging_middleware() -> Callable[
[str, dict[str, str], dict[str, Any]],
tuple[str, dict[str, str], dict[str, Any]],
]
Create middleware that logs request details
Source code in cocapi/middleware.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
add_request_id_middleware
¶
add_request_id_middleware() -> Callable[
[str, dict[str, str], dict[str, Any]],
tuple[str, dict[str, str], dict[str, Any]],
]
Create middleware that adds unique request ID to headers
Source code in cocapi/middleware.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
add_response_size_middleware
¶
add_response_size_middleware() -> Callable[
[dict[str, Any]], dict[str, Any]
]
Create middleware that adds response size information
Source code in cocapi/middleware.py
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | |
add_response_timestamp_middleware
¶
add_response_timestamp_middleware() -> Callable[
[dict[str, Any]], dict[str, Any]
]
Create middleware that adds processing timestamp to response
Source code in cocapi/middleware.py
163 164 165 166 167 168 169 170 171 172 173 174 | |
add_user_agent_middleware
¶
add_user_agent_middleware(
user_agent: str,
) -> Callable[
[str, dict[str, str], dict[str, Any]],
tuple[str, dict[str, str], dict[str, Any]],
]
Create middleware that adds custom User-Agent header
Source code in cocapi/middleware.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
create_dynamic_model
¶
create_dynamic_model(
response: dict[str, Any], endpoint_type: str
) -> dict[str, Any] | Any
Create a Pydantic model from JSON response.
First tries to match a concrete model from the schema registry. Falls back to dynamic model generation for unknown endpoints.
| PARAMETER | DESCRIPTION |
|---|---|
response
|
The JSON response data
TYPE:
|
endpoint_type
|
Type of endpoint (clan, player, etc.)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Any
|
Either a Pydantic model instance or the original dict |
Source code in cocapi/models.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | |
get_pydantic_info
¶
get_pydantic_info() -> dict[str, Any]
Get information about Pydantic availability and version
Source code in cocapi/models.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
validate_pydantic_available
¶
validate_pydantic_available() -> bool
Check if Pydantic is available for dynamic model creation
Source code in cocapi/models.py
122 123 124 | |
build_url
¶
build_url(
base_url: str,
endpoint: str,
params: dict[str, Any] | None = None,
) -> str
Build a complete URL with parameters
Source code in cocapi/utils.py
14 15 16 17 18 19 20 21 22 23 24 | |
clean_tag
¶
clean_tag(tag: str) -> str
Remove # prefix from clan/player tags if present
Source code in cocapi/utils.py
9 10 11 | |
validate_params
¶
validate_params(
params: dict[str, Any] | None,
valid_params: tuple[str, ...],
) -> bool
Validate that all parameters are in the allowed list
Source code in cocapi/utils.py
27 28 29 30 31 32 33 | |