---
title: "Turnstile in Python"
description: "A complete Python helper that returns a solved Turnstile token."
---

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

# Turnstile in Python

Install `requests`:

```bash
python -m pip install requests
```

```python title="turnstile.py"
import os
from typing import Any

import requests

API_URL = "https://api.uncaptcha.io/v1/task/execute"

class UncaptchaError(RuntimeError):
pass

def solve_turnstile(
*,
url: str,
sitekey: str,
proxy: str | None = None,
action: str | None = None,
cdata: str | None = None,
) -> str:
task_data: dict[str, Any] = {
    "url": url,
    "sitekey": sitekey,
}
if proxy:
    task_data["proxy"] = proxy
if action:
    task_data["action"] = action
if cdata:
    task_data["cdata"] = cdata

response = requests.post(
    API_URL,
    headers={"X-Api-Key": os.environ["UNCAPTCHA_API_KEY"]},
    json={"task_type": "turnstile", "task_data": task_data},
    timeout=35,
)

try:
    payload = response.json()
except requests.JSONDecodeError as exc:
    raise UncaptchaError(
        f"uncaptcha.io returned non-JSON status {response.status_code}"
    ) from exc

if not response.ok or not payload.get("success"):
    message = payload.get("message", "unknown uncaptcha.io error")
    raise UncaptchaError(f"{response.status_code}: {message}")

return payload["data"]["solution"]["token"]

if __name__ == "__main__":
token = solve_turnstile(
    url="https://example.com/register",
    sitekey="0x4AAAAAABs37s-ih7Jepz0J",
    proxy=os.getenv("SOLVE_PROXY"),
    action="register",
)
print(token)
```

Run it with:

```bash
UNCAPTCHA_API_KEY="your-api-key" \
SOLVE_PROXY="http://user:pass@203.0.113.10:8080" \
python turnstile.py
```

The helper returns only the token. If uncaptcha.io returns a structured error,
it raises `UncaptchaError` with the HTTP status and API message.

Source: https://docs.uncaptcha.io/examples/python-turnstile/index.mdx
