Skip to main content

CI Status Pypi version PyPI Downloads Documentation

Python version License Ruff

cocapi

A Python wrapper for the official Clash of Clans API with full async support, automatic key management, caching, retries, and optional Pydantic models.

Full Documentation

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 for or callbacks
  • Game data helpers — static game data lookups, army link parsing, CWL-aware current war, typed errors, per-call cache control
  • 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:

Credits

cocapi is not affiliated with SuperCell.

Metadata

Release files for cocapi 4.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cocapi 4.1.0
File Size Uploaded Provenance Actions
cocapi-4.1.0.tar.gz 194.8 kB Without provenance Details for cocapi-4.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cocapi 4.1.0
File Interpreter ABI Platform Actions
cocapi-4.1.0-py3-none-any.whl Python 3 none any Details for cocapi-4.1.0-py3-none-any.whl

Total release size: 273.3 kB

Release files / cocapi-4.1.0.tar.gz

Download URL cocapi-4.1.0.tar.gz
Size 194.8 kB
Tags Source
SHA-256 checksum
How to use checksums
c8fb31f79440dba964dd69e376b0b552c7bdff92f123f1f8785008d759d49ea8
BLAKE2b-256 checksum
How to use checksums
8cec6a44b97f7c082f6bb5cc66f0e4e852cdfe121e67ed26d32d79a1a8ab9365
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / cocapi-4.1.0-py3-none-any.whl

Download URL cocapi-4.1.0-py3-none-any.whl
Size 78.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cafc2702d417724e3da88bac5178d95c239e9c5f77e010275f0979843a2de9e3
BLAKE2b-256 checksum
How to use checksums
9dd65a6e2bcdd5ea54a4915279229ab7d2d05a6f70c016afffb6d2c49828c816
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for cocapi 4.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page