Integration 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 its token needs.
Before you start:
- 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 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 from Settings → My account → Security → API tokens works too.
- Store it on your server as an environment variable,
SOFIA_TOKEN. Never in browser or mobile code. - Set the workspace address and organization ID (see Your first call).
The shared set-up for all examples:
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 NoneCRM: create a task when a deal is won
Section titled “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.
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-43Store the task id and key on the deal. Later updates — a new due date, a changed manager — then go to PUT /tasks/{id} 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:
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 and Integration accounts.
ERP: comment and close the task when the invoice is paid
Section titled “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.
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.
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.
Publish a daily KPI page
Section titled “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.
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
Section titled “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 and The KPI report. The script below is for when you want your own counting rules.
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
Section titled “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-Keywith every create that may be retried. See Idempotency and retries. - Handle
429by waitingRetry-Afterseconds. See Rate limits. - Branch on
code, not on messages. See Errors. - Link records instead of storing keys where you can: an
externalRefon the task lets the other system find it again by its own ID. See Integrations API. - Prefer webhooks to polling. A webhook tells your system about changes as they happen. If you poll instead, poll gently: list tasks with
updatedFromset to today’s date (it counts whole days) every few minutes, and compare each task’supdatedAtwith what you stored.