> ## Documentation Index
> Fetch the complete documentation index at: https://www.worldmonitor.app/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 Python 按国家获取武装冲突数据

> 使用 Python 官方客户端 worldmonitor-sdk、REST 端点 /api/conflict/v1/list-ucdp-events 与免密钥沙盒示例，按国家代码查询活跃武装冲突事件、伤亡估计及 JMESPath 服务端裁剪结果，并对比原生 UCDP 数据源。

本指南提供可直接运行的 Python 代码片段，帮助你使用官方零依赖包 `worldmonitor-sdk` 按国家获取活跃武装冲突事件（注意：PyPI 上名为 `worldmonitor` 的包与本项目无关）。

## 1. 安装并运行 `worldmonitor-sdk`

```bash theme={null}
pip install worldmonitor-sdk
```

```python theme={null}
import os
from worldmonitor_sdk import Client

# 传入 api_key="wm_..." 或在环境变量中设置 WORLDMONITOR_API_KEY。
client = Client(api_key=os.environ["WORLDMONITOR_API_KEY"])

# 按 ISO 3166-1 alpha-2 国家代码拉取带地理坐标的 UCDP 暴力冲突事件。
payload = client.get(
    "/api/conflict/v1/list-ucdp-events",
    country="UA",
    jmespath="{version: candidateVersion, events: events[0:10].{id: id, country: country, deathsBest: deathsBest, dateStart: dateStart}}",
)

print(f"UCDP candidate version: {payload.get('version')}")
for event in payload.get("events", []):
    print(f"{event['country']} | deaths={event['deathsBest']} | start_ms={event['dateStart']} | id={event['id']}")
```

如果你希望通过 MCP 工具接口获取聚合后的冲突事件（包含 UCDP、骚乱与区域信息流），请传入**英文国家名**（例如 `"Ukraine"`）而非 ISO 两位代码：与上方的 `/api/conflict/v1/list-ucdp-events` 不同，`get_conflict_events` 按事件记录中的国家名称匹配 `country`（传入 `"UA"` 仅能匹配风险评分的地区代码，会漏掉乌克兰的冲突事件）：

```python theme={null}
result = client.conflict_events(country="Ukraine", limit=10)
print(result)
```

## 2. 免密钥体验（公开发现与沙盒样例）

在 [worldmonitor.app/pro](https://www.worldmonitor.app/pro) 签发密钥前，你可以分别使用免密钥 MCP 发现接口验证 SDK 连通性，并对静态沙盒样例执行免凭证 HTTP 冒烟测试（如需在断网 CI 中运行，可先将该 JSON 文件缓存到本地）。建议将两者拆开：匿名 MCP 发现不计入每日配额，但仍受 IP 速率限制（每 IP 每分钟 10 次），而静态沙盒文件可安全用于并行 CI。

**免密钥 MCP 发现**（无需 API 密钥验证 SDK 安装）：

```python theme={null}
from worldmonitor_sdk import Client

public_client = Client()
sources = public_client.call_tool("get_sources", view="summary")
print("Active source summary keys:", list(sources.keys()) if isinstance(sources, dict) else type(sources).__name__)
```

**确定性沙盒样例**（零凭证，适合并行 CI；注意当前 `sandbox/index.json` 尚未提供 `ListUcdpEvents` 样例，此处拉取 `get-country-risk.json` 用于验证 HTTP 客户端与沙盒外层结构，而非校验第 1 节的 UCDP 事件解析器）：

```python theme={null}
import json
import urllib.request

req = urllib.request.Request(
    "https://www.worldmonitor.app/sandbox/get-country-risk.json",
    headers={"User-Agent": "worldmonitor-python-guide/1.0 (+https://www.worldmonitor.app)"},
)
with urllib.request.urlopen(req, timeout=15) as response:
    fixture = json.loads(response.read().decode("utf-8"))

print("Sandbox operation:", fixture["operation"]["productionUrl"])
print("Sample envelope keys:", list(fixture["response"]["body"].keys()))
```

完整沙盒索引见 [沙盒与测试环境](https://www.worldmonitor.app/docs/zh/sandbox.md) 与 `https://www.worldmonitor.app/sandbox/index.json`。

## 3. 不使用 SDK 的直接 REST 请求

如偏好直接调用 HTTP，请携带清晰的 `User-Agent` 与 `X-WorldMonitor-Key`：

```bash theme={null}
curl -sS "https://api.worldmonitor.app/api/conflict/v1/list-ucdp-events?country=UA&jmespath=events%5B0%3A5%5D" \
  -H "X-WorldMonitor-Key: $WORLDMONITOR_API_KEY" \
  -H "User-Agent: my-conflict-script/1.0 (+https://example.com)"
```

## 何时选择 World Monitor 与原生 UCDP CSV

* **直接使用 UCDP**（[ucdp.uu.se](https://ucdp.uu.se/apidocs/)）：当你仅需 CC BY 4.0 许可的学术历史 CSV 批量下载时。
* **使用 World Monitor**：当你的脚本或 AI Agent 需要将 UCDP GED 与月度 Candidate 冲突事件与 GDELT 升级信号、国家不稳定指数（`/api/intelligence/v1/get-country-risk`）、航运中断及服务端 [JMESPath 裁剪](https://www.worldmonitor.app/docs/zh/mcp-jmespath.md) 统一在一个 API 密钥或 MCP Server 下查询时。
* 关于 ACLED：托管版 `worldmonitor.app` 不转售 ACLED 数据，默认冲突评分结合 UCDP 冲突底线与 GDELT 升级比率。详见 [CII 风险评分方法论](https://www.worldmonitor.app/docs/zh/methodology/cii-risk-scores.md) 与 [API 参考](https://www.worldmonitor.app/docs/zh/api-reference.md)。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.