Metadata-Version: 2.4
Name: tutorflow-content
Version: 0.1.0
Summary: Python client for the TutorFlow Content API: generated routes and models, retries, pagination, run polling and webhook verification.
License: Proprietary
Project-URL: Homepage, https://tutorflow.io/resources/integrations/content-api-sdks
Project-URL: Documentation, https://tutorflow.io/resources/integrations/content-api-sdks
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: httpx<1,>=0.27
Requires-Dist: attrs>=22.2
Requires-Dist: python-dateutil>=2.8
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: openapi-python-client==0.29.1; extra == "dev"

# tutorflow-content

A Python client for the TutorFlow Content API (`/v1/content`). Routes and models are generated from the published OpenAPI document with [openapi-python-client](https://github.com/openapi-generators/openapi-python-client), and the package adds what an integration otherwise writes by hand: retries, pagination, waiting for runs, typed errors, and webhook verification. It is built on httpx.

## Install

Requires Python 3.11 or later.

```bash
pip install tutorflow-content
```

Documentation is at [tutorflow.io/resources/integrations/content-api-sdks](https://tutorflow.io/resources/integrations/content-api-sdks).

## Create a client

Keep the key on your server.

```python
import os

from tutorflow_content import create_client, unwrap
from tutorflow_content.generated.api.content_classrooms import (
    content_integration_classroom_controller_list_classrooms as list_classrooms,
)

client = create_client(os.environ["TUTORFLOW_CONTENT_API_KEY"])

for classroom in unwrap(list_classrooms.sync_detailed(client=client)):
    print(classroom.id, classroom.name, classroom.is_sandbox)
```

Every route is a module under `tutorflow_content.generated.api.<tag>` with `sync`, `sync_detailed`, `asyncio` and `asyncio_detailed`. `unwrap()` takes a `*_detailed` response and returns the parsed model, or raises `ContentApiError` with `code`, `status`, `request_id`, `retry_after_seconds`, `current_etag` and `details` from the error envelope. A 412 raises its subclass `ContentPreconditionFailedError`.

A test key (`tf_content_test_...`) works the same way against the sandbox classroom; `is_test_key(api_key)` tells them apart.

## Retries and idempotency

`create_client()` installs `RetryTransport` (and `AsyncRetryTransport` for the async calls):

- `429`: always retried, after `Retry-After` (up to 60 seconds; a longer wait comes back to you as the 429).
- `500`, `502`, `503`, `504` and connection failures: retried only for `GET`, `PUT`, `DELETE` and requests that carry an `Idempotency-Key`, so a change is never applied twice.

Backoff starts at 0.5 s and doubles with jitter, two retries by default. Tune it with `create_client(key, retry=RetryConfig(max_retries=4))` or turn it off with `retry=None`.

Routes that accept an `Idempotency-Key` take it as the `idempotency_key=` argument. Every retry sends the same key, and the API replays the first answer:

```python
from tutorflow_content import new_idempotency_key
from tutorflow_content.generated.api.content_generation import content_generation_controller_generate_course as generate_course
from tutorflow_content.generated.models import ContentGenerateCourseRequest

accepted = unwrap(
    generate_course.sync_detailed(
        classroom_id,
        client=client,
        body=ContentGenerateCourseRequest(topic="Fractions for Grade 5", lesson_count=6, language="en"),
        idempotency_key=new_idempotency_key(),
    )
)
```

## Pagination

`paginate()` yields every item of a list and reads both envelopes: page-numbered lists get the next `page=`, cursor lists get `cursor=` from `meta.nextCursor`. Pass a function that takes those keyword arguments:

```python
from tutorflow_content import paginate
from tutorflow_content.generated.api.content_courses import content_resource_course_controller_list as list_courses

for course in paginate(lambda **next: list_courses.sync_detailed(classroom_id, client=client, limit=100, **next)):
    print(course.id, course.title)
```

## Waiting for runs

These poll until the run settles and return its final status. They do not raise when the run failed; check the status.

```python
from tutorflow_content import wait_for_build, wait_for_render, wait_for_run

run = wait_for_run(client, classroom_id=classroom_id, run_id=accepted.run_id)  # tests, modules, courses, slides
if str(run.status) == "failed":
    raise RuntimeError(run.error)

build = wait_for_build(client, kind="game", classroom_id=classroom_id, resource_id=game_id, run_id=run_id)
render = wait_for_render(client, classroom_id=classroom_id, video_id=video_id)
```

Options: `interval` (default 3 s), `timeout` (default 30 minutes), `on_poll`. The build status route only knows runs of the server that answers since its last deploy; a run it no longer tracks raises `ContentWaitError` with `reason == "run_not_tracked"`, and the run's webhook is the signal to rely on.

## Webhooks

`verify_webhook()` checks the `X-Content-Integration-Signature-V2` header against the raw body and returns the event as a dict, with `livemode` always present:

```python
from flask import Flask, abort, request

from tutorflow_content import WebhookVerificationError, verify_webhook

app = Flask(__name__)
SECRETS = [s for s in (os.environ.get("TUTORFLOW_WEBHOOK_SECRET"), os.environ.get("TUTORFLOW_WEBHOOK_SECRET_PREVIOUS")) if s]


@app.post("/tutorflow/webhooks")
def tutorflow_webhook():
    try:
        event = verify_webhook(request.get_data(), request.headers.get("X-Content-Integration-Signature-V2"), SECRETS)
    except WebhookVerificationError as error:
        abort(400, error.reason)

    if event["event"]["type"] == "course.generation.completed" and event["livemode"]:
        queue_course_import(event["event"]["id"], event["resourceId"])
    return "", 204
```

It accepts the request when `t` is within `tolerance_seconds` (default 300) of now and any `v1=` signature matches any secret you pass. During TutorFlow's secret rotation grace period the header carries a signature for the new and the previous secret. Deliveries are signed again on every retry.

## Development

```bash
cd sdks/python
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
pytest                               # httpx.MockTransport, no network
python scripts/generate.py           # rewrite tutorflow_content/generated
python scripts/generate.py --check   # exit 1 when it is stale against openapi.json
```

`tutorflow_content/generated` comes from `apps/frontend-admin/public/resources/integrations/openapi.json`, which the backend writes (`pnpm run openapi:content -- <path>` in tutorflow-backend). Regenerate after that file changes and commit both. Do not edit the generated code by hand.
