Async & sync Python wrapper for the Clash of Clans API with auto key management
Project description
cocapi
A Python wrapper for the official Clash of Clans API with full async support, automatic key management, caching, retries, and optional Pydantic models.
Features
- Sync & async — same methods, same names, both modes
- Automatic key management — login with email/password, keys are created, reused, and rotated automatically
- Caching — TTL-based response caching with stats
- Retries — exponential backoff for rate limits and server errors
- Pagination & batch —
paginate()auto-follows cursors,batch()fetches many resources at once - Event polling — real-time monitoring of clans, wars, and players with
async foror callbacks - Pydantic models — optional typed response objects with IDE autocompletion
- Middleware — plug in custom request/response processing
- CLI —
cocapi clan "#2PP"from the terminal - Maintenance detection — automatic detection of API maintenance windows
Install
pip install cocapi
# With Pydantic model support
pip install 'cocapi[pydantic]'
# With CLI
pip install 'cocapi[cli]'
Requires Python 3.10+.
Quick Start
With an API Token
Get a token from developer.clashofclans.com:
from cocapi import CocApi
api = CocApi("your_api_token")
clan = api.clan_tag("#2PP")
print(clan["name"])
player = api.players("#900PUCPV")
print(player["trophies"])
With Email/Password (Automatic Key Management)
Skip manual key creation entirely. cocapi logs into the developer portal, detects your IP, and manages keys for you:
from cocapi import CocApi
api = CocApi.from_credentials("you@example.com", "your_password")
clan = api.clan_tag("#2PP")
Keys are created automatically, reused when valid, and rotated when your IP changes. See the Authentication guide for details.
Async
import asyncio
from cocapi import CocApi
async def main():
async with CocApi("your_token") as api:
clan = await api.clan_tag("#2PP")
player = await api.players("#900PUCPV")
print(clan["name"], player["trophies"])
asyncio.run(main())
See the Async guide for more patterns.
Configuration
All options are set through ApiConfig:
from cocapi import CocApi, ApiConfig
config = ApiConfig(
timeout=30,
max_retries=3,
enable_caching=True,
cache_ttl=600,
enable_rate_limiting=True, # async only
requests_per_second=10.0,
enable_metrics=True,
use_pydantic_models=True, # requires cocapi[pydantic]
)
api = CocApi("your_token", config=config)
See the Configuration guide for all options.
Pagination & Batch
# Auto-paginate through all clan members
for member in api.paginate(api.clan_members, "#CLAN_TAG"):
print(member["name"])
# Fetch multiple players at once
results = api.batch(api.players, ["#TAG1", "#TAG2", "#TAG3"])
Both work in sync and async. See the Pagination & Batch guide.
Event Polling
Monitor clans, wars, and players in real time. Async only.
from cocapi.events import EventStream, EventType
async with CocApi("token") as api:
stream = EventStream(api)
stream.watch_clans(["#2PP"], interval=60)
stream.watch_wars(["#2PP"], interval=30)
stream.watch_players(["#900PUCPV"], interval=120)
async with stream:
async for event in stream:
print(event.event_type, event.tag)
for change in event.changes:
print(f" {change.field}: {change.old_value} -> {change.new_value}")
Supports 20+ event types including member join/leave, war state transitions, troop/hero upgrades, maintenance detection, and more. See the Event Polling guide.
CLI
pip install 'cocapi[cli]'
# Login once (key is persisted)
cocapi login --email you@example.com --password yourpass
# Use without --token
cocapi clan "#2PP"
cocapi player "#900PUCPV"
cocapi war "#2PP"
cocapi search "clash" --limit 5
cocapi goldpass
See the CLI guide for all commands.
Error Handling
All endpoints return a dict (or Pydantic model). Errors never raise exceptions:
result = api.clan_tag("#INVALID")
if result.get("result") == "error":
print(result["message"]) # Human-readable message
print(result["error_type"]) # "timeout", "connection", "http", "json", etc.
print(result.get("status_code"))
See the Error Handling guide.
Examples
Runnable scripts in the examples/ folder:
| Script | What it covers |
|---|---|
basic_usage.py |
Sync: clan info, player info, search, error handling |
async_usage.py |
Async with context manager, concurrent requests |
credential_auth.py |
Email/password login, key persistence, auto-refresh |
pagination_batch.py |
paginate() and batch() in sync and async |
event_polling.py |
EventStream with async for — real-time monitoring |
event_callbacks.py |
@stream.on() decorators and stream.run() |
configuration.py |
ApiConfig, caching, metrics, middleware |
API Reference
Full API reference with all endpoints, parameters, and response schemas is available in the documentation.
Key classes:
CocApi— main entry point (sync/async)ApiConfig— configuration optionsEventStream— real-time event polling- Pydantic Schemas — typed response models
- All Endpoints — every API method
Credits
cocapi is not affiliated with SuperCell.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cocapi-4.0.1.tar.gz.
File metadata
- Download URL: cocapi-4.0.1.tar.gz
- Upload date:
- Size: 146.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0bee9b279d5cee4494ce9489316a4e765cd1e7a2f4599ca5c8b5df814c9eb246
|
|
| MD5 |
c4a2aad4d4631840c6f04f2d3587c53c
|
|
| BLAKE2b-256 |
640f3e295166193122dd57dadec56245d859f056483d4bfe77e609ade03e3d94
|
File details
Details for the file cocapi-4.0.1-py3-none-any.whl.
File metadata
- Download URL: cocapi-4.0.1-py3-none-any.whl
- Upload date:
- Size: 70.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
68d142822400f9a8bf603e0002321e87240f50d2ed7a9a51df947d44c62726e3
|
|
| MD5 |
6deb46f52698854b5a25f3bfb222f83e
|
|
| BLAKE2b-256 |
a7e791f7c5be4b7ed7b093ca9ff1dad86ef3bdce424a5cc16b9b93f0a0ee2159
|