# Integration examples

> Complete, copy-ready examples of connecting a CRM, an ERP and a KPI report to Sofia Space through the API — create a task when a deal is won, close it when the invoice is paid, publish a daily KPI page, and count finished work per person.

Source: https://docs.sofiaspace.uz/api/examples/

These examples show whole integrations, not single calls. They are written in Python with the `requests` library, but every step is a plain HTTP call you can make from any language — 1C, PHP, Node.js, Go. Each example says which [scopes](https://docs.sofiaspace.uz/api/authentication.md#scopes) its token needs.

**Before you start:**

1. Get a token with the scopes the example lists. For a company system — a CRM, an ERP, a KPI tool — an Org Admin creates an [integration account](https://docs.sofiaspace.uz/integrations/integration-accounts.md) and a token for it in **Settings → Integrations**: it uses no seat, everything it does shows its name with an **Integration** badge, and it keeps working when an employee leaves. For a script of your own, a [personal API token](https://docs.sofiaspace.uz/integrations/api-tokens.md) from **Settings → My account → Security → API tokens** works too.
2. Store it on your server as an environment variable, `SOFIA_TOKEN`. Never in browser or mobile code.
3. Set the workspace address and organization ID (see [Your first call](https://docs.sofiaspace.uz/api/overview.md#your-first-call-in-three-steps)).

The shared set-up for all examples:

```python
import json, os, requests

BASE = "https://acme.sofiaspace.uz/api/v1"
ORG_ID = "6b1f0c3e-2a4d-4c55-9a51-0d3f6a1e7b20"
S = requests.Session()
S.headers["Authorization"] = f"Bearer {os.environ['SOFIA_TOKEN']}"

def call(method, path, **kw):
    r = S.request(method, BASE + path, timeout=30, **kw)
    if r.status_code >= 400:
        raise RuntimeError(f"{method} {path} -> {r.status_code}: {r.text}")
    return r.json() if r.content else None
```

## CRM: create a task when a deal is won

**Scopes:** `tasks:read`, `tasks:write`.

When a deal moves to **Won** in your CRM, open an onboarding task in the `SALES` project, assigned to the account manager, due in seven days. The idempotency key is built from the deal number, so the CRM can safely resend the webhook.

```python
import datetime

def project_by_key(key):
    projects = call("GET", f"/orgs/{ORG_ID}/projects")["projects"]
    return next(p for p in projects if p["key"] == key)

def task_type_id(name):
    types = call("GET", f"/orgs/{ORG_ID}/task-types")["taskTypes"]
    return next(t["id"] for t in types if t["name"] == name)

def user_id_by_email(email):
    members = call("GET", f"/orgs/{ORG_ID}/members/search", params={"q": email})["members"]
    return next(m["userId"] for m in members if m["email"].lower() == email.lower())

def on_deal_won(deal):
    project = project_by_key("SALES")
    due = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()
    task = call(
        "POST", f"/projects/{project['id']}/tasks",
        headers={"Idempotency-Key": f"crm-deal-{deal['number']}-onboarding"},
        json={
            "taskTypeId": task_type_id("Task"),
            "title": f"Onboard {deal['company']} (deal #{deal['number']})",
            "description": f"Deal value: {deal['amount']:,} so'm\nContact: {deal['contact']}",
            "assigneeId": user_id_by_email(deal["manager_email"]),
            "priority": "HIGH",
            "dueDate": due,
        },
    )
    key = f"{project['key']}-{task['taskNumber']}"
    return task["id"], key   # store both on the CRM deal

task_id, key = on_deal_won({
    "number": 1042, "company": "Client A", "amount": 125_000_000,
    "contact": "+998 90 123 45 67", "manager_email": "ali.valiyev@example.com",
})
print("Created", key)   # Created SALES-43
```

Store the task `id` and key on the deal. Later updates — a new due date, a changed manager — then go to [`PUT /tasks/{id}`](https://docs.sofiaspace.uz/api/tasks.md#update-a-task) instead of creating a second task.

The idempotency key only protects against repeats within ten minutes. For a CRM, the **create-by-key** call made for other systems is shorter and safer: one request takes the project key, the type and status by name and the assignee by e-mail, and links the task to the deal with an `externalRef`. If a task you can open is already linked to that deal, you get that task back (`200`, header `X-Sofia-Existing: true`) instead of a second one — at any time, not just within ten minutes:

```python
def on_deal_won(deal):
    due = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()
    task = call("POST", f"/orgs/{ORG_ID}/projects/by-key/SALES/tasks", json={
        "type": "Task",
        "title": f"Onboard {deal['company']} (deal #{deal['number']})",
        "assignee": deal["manager_email"],
        "priority": "HIGH",
        "dueDate": due,
        "externalRef": {"system": "crm", "id": str(deal["number"]),
                        "label": f"Deal #{deal['number']}"},
    })
    return task["id"], f"SALES-{task['taskNumber']}"
```

Same scope (`tasks:write`). See [Integrations API](https://docs.sofiaspace.uz/api/integrations.md) and [Integration accounts](https://docs.sofiaspace.uz/integrations/integration-accounts.md).

## ERP: comment and close the task when the invoice is paid

**Scopes:** `tasks:read`, `tasks:write`.

The ERP knows the task key (`SALES-43`) the CRM stored. When the invoice is paid, find the task, leave a comment and move it to the project's done status. If the workflow refuses the move — an open subtask, an unfinished blocker — leave it and report why.

```python
def task_by_key(task_key):
    project_key, number = task_key.rsplit("-", 1)
    return call("GET", f"/projects/by-key/{project_key}/tasks/{number}/summary")

def done_status_id(project_id):
    statuses = call("GET", f"/projects/{project_id}/workflow-statuses")["statuses"]
    return next(s["id"] for s in statuses if s["statusGroup"] == "DONE")

def on_invoice_paid(task_key, invoice_no):
    task = task_by_key(task_key)   # id, taskNumber, title, statusId, projectId, done …
    if task["done"]:
        return "Already done"
    call("POST", f"/tasks/{task['id']}/comments",
         json={"content": f"Invoice {invoice_no} paid in full."})
    r = S.post(f"{BASE}/tasks/{task['id']}/status", timeout=30,
               json={"newStatusId": done_status_id(task["projectId"])})
    if r.status_code == 409:
        # INVALID_TRANSITION, INCOMPLETE_SUBTASKS or BLOCKED_BY_INCOMPLETE_TASK
        return f"Not closed: {r.json()['error']}"
    r.raise_for_status()
    return "Closed"

print(on_invoice_paid("SALES-43", "2026/114"))
```

If the workflow has no direct move from the current status to the done one, move through the statuses in between, using [the transitions list](https://docs.sofiaspace.uz/api/projects.md#list-allowed-transitions).

If the task was created with an `externalRef` (see the CRM example), the ERP doesn't need the key at all: `GET /api/v1/orgs/{orgId}/tasks/by-external-ref?system=crm&id=1042` (scope `tasks:read`) returns the task linked to deal 1042, or `404` when there is none you can open. See [Integrations API](https://docs.sofiaspace.uz/api/integrations.md).

## Publish a daily KPI page

**Scopes:** `docs:read`, `docs:write` — or only `doc:create` if the script never reads.

Every morning, a job reads yesterday's numbers from your ERP and publishes them as a page in the `OPS` space. The first run creates the page; later runs publish a new version into it, so the page's history keeps every day.

```python
def text(t, bold=False):
    node = {"type": "text", "text": t}
    if bold:
        node["marks"] = [{"type": "bold"}]
    return node

def kpi_document(day, rows):
    return {"type": "doc", "content": [
        {"type": "heading", "attrs": {"level": 2}, "content": [text(f"Sales KPI for {day}")]},
        {"type": "bulletList", "content": [
            {"type": "listItem", "content": [{"type": "paragraph", "content": [
                text(f"{name}: ", bold=True), text(f"{value:,} so'm")]}]}
            for name, value in rows
        ]},
        {"type": "paragraph", "content": [text("Updated automatically from the ERP.")]},
    ]}

SPACE_ID = "5a7c9e1b-3d5f-4a8c-b2e4-6f8a1c3e5d79"
PAGE_ID = os.environ.get("KPI_PAGE_ID")   # empty on the first run

if not PAGE_ID:
    page = call("POST", f"/spaces/{SPACE_ID}/pages",
                headers={"Idempotency-Key": "kpi-daily-page"},
                json={"title": "Sales KPI (daily)"})
    PAGE_ID = page["id"]    # save it for the next runs

doc = kpi_document("13 November 2026", [("Tashkent", 640_000_000), ("Samarkand", 410_000_000)])
version = call("POST", f"/pages/{PAGE_ID}/publish",
               json={"content": json.dumps(doc, ensure_ascii=False)})
print("Published version", version["versionNumber"])
```

Note `json.dumps(doc)`: the page content is a **string** inside the JSON body. The `requests` library then serializes the body itself, so the document ends up encoded twice — that's correct.

## Count finished work per person for a weekly KPI

**Scopes:** `tasks:read`.

Count the tasks each person finished last week across two projects, using Tashkent dates, and turn user IDs into names.

If you only need the standard numbers, there's a ready-made report: `GET /api/v1/orgs/{orgId}/kpi?from=2026-11-09&to=2026-11-15&tz=Asia/Tashkent` (scope `dashboards:read`) returns one row per person with name, e-mail, tasks completed, points, on-time rate, open and overdue tasks, median cycle days and hours logged, the same numbers dashboards show — add `projectIds`, `groupBy=week` or `format=csv` as needed. Everyone's rows need the same right as a dashboard's People view; otherwise you get only your own. See [Integrations API](https://docs.sofiaspace.uz/api/integrations.md) and [The KPI report](https://docs.sofiaspace.uz/integrations/integration-accounts.md#the-kpi-report). The script below is for when you want your own counting rules.

```python
from collections import Counter

def finished(project_id, start, end):
    params = {"doneFrom": start, "doneTo": end, "tz": "Asia/Tashkent",
              "description": "false", "limit": 100}
    while True:
        page = call("GET", f"/projects/{project_id}/tasks", params=params)
        yield from page["items"]
        if not page["hasMore"]:
            return
        params["cursor"] = page["nextCursor"]

counts = Counter()
for key in ("SALES", "OPS"):
    for task in finished(project_by_key(key)["id"], "2026-11-09", "2026-11-15"):
        counts[task["assigneeId"]] += 1

ids = [u for u in counts if u]
users = call("POST", "/users/batch-get", json={"userIds": ids})["users"]
names = {u["userId"]: f"{u['firstName']} {u['lastName']}" for u in users}
for user_id, n in counts.most_common():
    print(names.get(user_id, "Unassigned"), n)
```

## Things to get right in every integration

- **Look things up by key or e-mail, store IDs.** Project keys, status IDs and user IDs don't change when names are renamed or translated; names do.
- **Send an `Idempotency-Key` with every create** that may be retried. See [Idempotency and retries](https://docs.sofiaspace.uz/api/idempotency.md).
- **Handle `429`** by waiting `Retry-After` seconds. See [Rate limits](https://docs.sofiaspace.uz/api/rate-limits.md).
- **Branch on `code`, not on messages.** See [Errors](https://docs.sofiaspace.uz/api/errors.md).
- **Link records instead of storing keys** where you can: an `externalRef` on the task lets the other system find it again by its own ID. See [Integrations API](https://docs.sofiaspace.uz/api/integrations.md).
- **Prefer webhooks to polling.** A [webhook](https://docs.sofiaspace.uz/integrations/webhooks.md) tells your system about changes as they happen. If you poll instead, poll gently: list tasks with `updatedFrom` set to today's date (it counts whole days) every few minutes, and compare each task's `updatedAt` with what you stored.

## Related

- [API overview](https://docs.sofiaspace.uz/api/overview.md)
- [Integrations API](https://docs.sofiaspace.uz/api/integrations.md)
- [Integration accounts](https://docs.sofiaspace.uz/integrations/integration-accounts.md)
- [Tasks](https://docs.sofiaspace.uz/api/tasks.md)
- [Spaces and pages](https://docs.sofiaspace.uz/api/spaces-and-pages.md)
- [Connect your tools](https://docs.sofiaspace.uz/guides/connect-your-tools.md)
