CosmosIQ KIWAN · Developer & API Hub

One Integration. Multiple Learning Ecosystems.

Deliver CosmosIQ course video, theory, MCQ and mind maps inside your own LMS, portal or app, according to the package agreed for each course. Register learners, enrol them in the courses assigned to your institute, and stream lessons from your own pages.

Powered by CosmosIQUniversityCollegeLMSEdTechAPI v1SandboxLive Integration
Base URLhttps://cosmosiq.ai/api/kiwan/v1
FormatJSON over HTTPS
AuthAPI key (Bearer)
PostmanDownload collection
OverviewAbout KIWAN, catalogue and access request

Quick start

  1. Get your keys. CosmosIQ gives you a sandbox key (for building and testing) and a live key (for production). Keep them on your server; never put a key in browser code.
  2. Check the connection.
    curl https://cosmosiq.ai/api/kiwan/v1/me -H "Authorization: Bearer YOUR_KEY"
  3. See your courses with GET /courses, then the syllabus with GET /courses/{id}/syllabus.
  4. Enrol a learner with POST /enrollments (name, email and mobile are compulsory for every learner).
  5. Show a lesson with GET /lessons/{id}?email=...: put the returned stream_url in a <video> tag, or render the theory HTML. Practice questions come from GET /mcq/{set_id}.
  6. Report progress back with POST /progress and read it with GET /enrollments (see Progress synchronization).

Integration architecture

Your system calls the KIWAN API from its server; the API returns learner-ready content and signed video links, and your LMS shows them to the learner. The browser never holds an API key.

Typical request flow

  1. The learner signs in to your LMS (you keep your own login).
  2. Your server calls POST /enrollments once per learner and course.
  3. When the learner opens a lesson, your server calls GET /lessons/{id}?email=... and passes the result to the page.
  4. As the learner moves ahead, your server reports POST /progress.
  5. Your reports read GET /enrollments and GET /usage.

Authentication guide

Every call except GET /health needs an API key. Send it as Authorization: Bearer kiwan_live_... (or kiwan_sandbox_...). The header X-Kiwan-Key is also accepted. Keys are never accepted in the URL.

Step by step

  1. Receive keys. Keys are shown to you once when CosmosIQ issues them. Store them in an environment variable or secret manager, never in source code or a browser.
  2. Choose the environment. kiwan_sandbox_... validates your requests but never saves learners, enrolments or progress, and is never billed; kiwan_live_... is for production. Switching is one value.
  3. Register your domains. The domains of your LMS are registered with CosmosIQ. A request (or video link) carrying an Origin or Referer from any other domain is refused with origin_not_allowed. Server-to-server calls normally send no Origin header and are not affected.
  4. Optional IP allow-list. Restrict your key to your server addresses; others get ip_not_allowed.
  5. Verify. GET /me shows your institute, environment, registered domains, courses assigned, contract end date and your rate limit.

Key rotation

Ask CosmosIQ to rotate your live key. The new key works immediately and the old key keeps working for an overlap period (24 hours by default), so you can switch without downtime. After the overlap the old key returns key_expired.

Revoking a key (emergency procedure)

  1. If a key may have leaked, contact CosmosIQ immediately through your account manager and name the key (the first characters, for example kiwan_live_ab12cd34, are enough; never send the full key).
  2. CosmosIQ revokes the key. From then on it returns 401 key_revoked; the change takes effect within about a minute.
  3. A replacement key is issued and shown once. Deploy it, then confirm with GET /me.
  4. Review recent activity for that key (see API audit logs) and tell us if anything looks unexpected.

Sandbox and live

Sandbox key kiwan_sandbox_...Live key kiwan_live_...
Learners / enrolments / progressValidated, not saved (response has "sandbox": true, "persisted": false)Saved
LessonsSample content: in each assigned course the first video lesson, the first theory lesson and (when mind maps are in your package) the first lesson that has a mind map, plus free-preview lessons. No email needed.All lessons of assigned courses, for enrolled learners
MCQThe set list works; the questions of the first set of each course can be openedAll sets, for enrolled learners, if MCQ is in your package
BillingNever countedCounted per learner per course

The syllabus marks the sandbox samples with "sample": true. Build against the sandbox, then switch to the live key by changing one value. A sandbox key still follows your package: content outside the package returns not_in_package.

Conventions

Learner data

For every learner we need name, email and mobile. consent_marketing should be true only if the learner has agreed to receive CosmosIQ updates; leave it false or omit it otherwise. institute_student_id is your own reference and is returned as-is.

A learner who later signs in to CosmosIQ with the same email sees the KIWAN courses under My Learning automatically.

Your content package

For every course assigned to you, CosmosIQ switches on the parts you have taken. The API returns only those parts.

PartWhat it isWhere you get it
VideoLesson videos hosted by CosmosIQGET /lessons/{id} (video.stream_url)
TheoryStudy notes: text, tables, key points, key terms, common mistakes, practice questionsGET /lessons/{id} (theory)
MCQLesson quizzes and module tests (answers and explanations are available to your server)GET /courses/{id}/mcq, GET /mcq/{set_id}
Mind mapA visual mind map per lesson (SVG and structured nodes)GET /lessons/{id} (mindmap)

The package for each course is in GET /courses (package). Asking for anything outside it returns 403 not_in_package, and it is left out of the syllabus. Not every course has every part yet: check the counts (videos, theory_lessons, mcq_sets, mindmaps) in GET /courses.

Playing video

  1. Call GET /lessons/{id}?email=learner@... from your server when the learner opens the lesson.
  2. Give the returned video.stream_url to your player: <video controls src="STREAM_URL">. Seeking works (HTTP range requests).
  3. The link is signed and expires after 2 hours (expires_at). Never store it; request a fresh one each time the lesson is opened.
  4. The link is checked against your registered domains whenever the request carries an Origin or Referer header, as browsers send for video playback. This is a safeguard, not DRM: the signed, expiring link is the main protection, so request it from your server and never publish it. Pausing or ending the contract stops playback within a few seconds.
<video controls playsinline preload="metadata" src="https://cosmosiq.ai/api/kiwan/v1/stream/..."></video>

Showing theory

The mind map of a lesson is delivered separately (see below), so it is not part of theory.html.

Theory lessons come as theory.html (safe, theme-neutral HTML using only headings, paragraphs, lists, tables, quotes, code and links; no scripts, styles or images) and/or theory.blocks (structured JSON) so you can render with your own design. Choose with format=html|json|both.

{ "type": "heading",   "level": 2, "text": "..." }
{ "type": "paragraph", "text": "..." }
{ "type": "list",      "ordered": false, "items": ["...", "..."] }
{ "type": "table",     "headers": ["A","B"], "rows": [["1","2"]] }
{ "type": "quote",     "text": "..." }
{ "type": "code",      "text": "..." }

MCQ practice

  1. GET /courses/{id}/mcq lists the sets (lesson quizzes and module tests).
  2. GET /mcq/{set_id}?email=learner@... returns the questions. Options are a to d. correct_option and explanation are included by default; send answers=false to leave them out. Always use answers=false for anything a learner's browser can read.
  3. Collect the learner's answers on your server, then fetch the same set with answers (a server-side call without answers=false) and grade there. Show correct answers and explanations only after submission, or in a review mode you control.
  4. If you want the learner's course progress on CosmosIQ updated, report it with POST /progress.

Assessment integrity

Mind maps

When mind maps are in your package, GET /lessons/{id} for a theory lesson that has one returns mindmap:

"mindmap": {
  "svg": "<svg viewBox=...>...</svg>",
  "nodes": { "center": "Indian Banking System",
             "branches": [ { "title": "Core functions", "items": ["Accept deposits", "Lend and invest"] } ] }
}

Show the svg as it is (it scales to any width) or draw your own map from nodes. The SVG is cleaned: only shapes and text, no scripts.

Progress synchronization

Your LMS knows what the learner did inside your pages, so your system reports progress and CosmosIQ stores it against the enrolment. CosmosIQ itself records first_accessed_at and last_accessed_at whenever a lesson is opened through the API.

DirectionCallWhat it does
You → CosmosIQPOST /progressSend progress_pct (0-100) for an email and course. 100 marks the enrolment completed and sets completed_at.
CosmosIQ → youGET /enrollments?email=&course_id=&status=Returns status, progress_pct, enrolled_at, first_accessed_at, last_accessed_at, completed_at. Paginated with after.
StatusPATCH /enrollments/{id}Set active, cancelled or completed.
ReconciliationGET /usage?from=&to=Enrolled, billable and active learners and lesson opens per course.

Recommended pattern

  1. Report progress when a lesson or quiz is completed, not on every click. Send the highest value reached; never send a lower value than before.
  2. Use a fresh Idempotency-Key per report so retries are safe.
  3. Run a nightly job that pages through GET /enrollments?status=active and compares it with your own records. Treat your LMS as the source of truth for in-LMS activity.
  4. A cancelled enrolment cannot receive progress (enrollment_cancelled); set it back to active first.
curl -X POST "$BASE/progress" \
  -H "Authorization: Bearer $KIWAN_KEY" -H "Idempotency-Key: prog-5120-60-2026-07-01" \
  -H "Content-Type: application/json" \
  -d '{ "email": "student@example.com", "course_id": 306, "progress_pct": 60 }'

curl "$BASE/enrollments?email=student@example.com&course_id=306" -H "Authorization: Bearer $KIWAN_KEY"

Content updates

Content is served live from CosmosIQ. When a lesson, quiz or mind map is revised, the next request returns the revised version; there is nothing to re-import. Syllabus data can be cached for a short time on our side.

Access, pause and contract end

Usage and billing

Billing is per learner per course at the rate agreed for that course and package, counted when a learner is first enrolled. Enrolling the same learner in the same course again, or cancelling and re-activating, does not create another charge. GET /usage shows enrolled and active learners for any period so you can reconcile with your invoice.

Endpoints

GET/healthHealth check

Public, no key needed. Use it for uptime monitoring.

Example response
{"data":{"status":"ok","database":"ok","version":"1","time":"2026-07-01T09:30:00.000Z"},"request_id":"..."}
GET/meWho am I

Shows your institute, environment (live or sandbox), registered domains, contract end date and your rate limit.

Example response
{"data":{"institute_id":"KWN-7K2M9QXA","name":"Example University","status":"active","currency":"INR","contract_end":"31/03/2027","environment":"live","domains":["lms.example.edu"],"courses_assigned":12,"rate_limit_per_min":600}}
GET/coursesList your courses

Only courses assigned to your institute. package shows which content types you can use for each course; counts for content outside your package are 0. content_status is ready or coming_soon (based on your package).

Example response
{"data":{"items":[{"id":306,"slug":"...","title":"Indian Banking System","level":"Beginner","modules":9,"package":{"video":true,"theory":true,"mcq":true,"mindmap":false},"videos":69,"theory_lessons":77,"video_minutes":1261,"mcq_sets":69,"mcq_questions":1313,"mindmaps":0,"content_status":"ready","thumbnail_url":"https://..."}]}}
GET/courses/{course_id}/syllabusCourse syllabus

Modules with lessons and MCQ sets, limited to your package. Each lesson lists parts: what you can open from it (video, theory, mindmap). MCQ sets appear only if MCQ is in your package.

Example response
{"data":{"course_id":306,"title":"...","package":{"video":true,"theory":true,"mcq":true,"mindmap":false},"modules":[{"id":1,"number":1,"title":"...","lessons":[{"id":4521,"title":"...","type":"video","parts":["video"],"duration_minutes":9,"free_preview":false}],"mcq_sets":[{"id":88,"title":"...","total_questions":15}]}]}}
GET/lessons/{lesson_id}?email=&format=Open a lesson

Live keys need ?email= of an enrolled learner; sandbox keys open the sample lessons only. format = html | json | both (theory only). Video lessons return a signed stream_url valid for 2 hours; request a fresh one when it expires. Theory is returned as sanitised HTML and/or structured blocks (heading, paragraph, list, table, quote, code). If your package includes mind maps and the lesson has one, it comes as mindmap (svg + nodes). Anything outside your package returns not_in_package.

Example response
{"data":{"id":4521,"course_id":306,"title":"...","type":"video","duration_minutes":9,"video":{"stream_url":"https://cosmosiq.ai/api/kiwan/v1/stream/...","expires_at":"2026-07-01T11:30:00.000Z","expires_in":7200,"format":"video/mp4"}}}
GET/courses/{course_id}/mcqList MCQ sets

Needs MCQ in your package for the course. Returns lesson quizzes and module tests with question counts, time limit and passing score.

Example response
{"data":{"course_id":306,"sets":[{"id":4294,"module_id":2017,"module_number":1,"module_title":"...","set_number":1,"title":"L1.1 ...","difficulty":"mixed","total_questions":15,"time_limit_minutes":15,"passing_score_pct":70}]}}
GET/mcq/{set_id}?email=&answers=Get the questions of an MCQ set

Live keys need ?email= of an enrolled learner; sandbox keys can open the first set of each course. Each question has four options (a-d). By default correct_option and explanation are included, meant for your server (grading, review). For anything a learner browser can read, send answers=false.

Example response
{"data":{"id":4294,"course_id":306,"title":"L1.1 ...","total_questions":15,"time_limit_minutes":15,"passing_score_pct":70,"questions":[{"id":174966,"number":1,"text":"...","options":[{"key":"a","text":"..."},{"key":"b","text":"..."},{"key":"c","text":"..."},{"key":"d","text":"..."}],"difficulty":"easy","topic":"...","correct_option":"a","explanation":"..."}]}}
POST/learnersCreate or update a learner

name, email and mobile are compulsory. consent_marketing (true/false) and institute_student_id are optional. Same email again updates the record (200); a new learner returns 201.

Request body
{"name":"Asha Verma","email":"asha@college.edu","mobile":"+919876543210","consent_marketing":true,"institute_student_id":"BBA-2026-014"}
Example response
{"data":{"created":true,"id":991,"name":"Asha Verma","email":"asha@college.edu","mobile":"+919876543210","consent_marketing":true,"institute_student_id":"BBA-2026-014"}}
GET/learners?email= | ?limit=&after=Get or list learners

With ?email= returns one learner. Without it, returns a page (limit up to 200) and next_after for the next page.

Example response
{"data":{"items":[{"id":991,"name":"...","email":"..."}],"next_after":null}}
POST/enrollmentsEnrol a learner in a course

Send email, or a full learner object to create-and-enrol in one call. Enrolling again is safe and returns the existing enrolment. Optional enrolled_at (ISO date).

Request body
{"course_id":306,"email":"asha@college.edu"}
Example response
{"data":{"created":true,"reactivated":false,"learner_created":false,"id":5120,"email":"asha@college.edu","course_id":306,"status":"active","progress_pct":0}}
GET/enrollments?email=&course_id=&status=&limit=&after=List enrolments

Filter by learner, course or status (active, cancelled, completed). Paginated.

Example response
{"data":{"items":[{"id":5120,"email":"...","course_id":306,"status":"active","progress_pct":42.5,"first_accessed_at":"...","last_accessed_at":"..."}],"next_after":null}}
PATCH/enrollments/{id}Change enrolment status

status = active | cancelled | completed.

Request body
{"status":"cancelled"}
Example response
{"data":{"id":5120,"status":"cancelled", "...":"..."}}
POST/progressReport learner progress

Send progress_pct (0-100) for a learner and course. 100 marks the enrolment completed.

Request body
{"email":"asha@college.edu","course_id":306,"progress_pct":60}
Example response
{"data":{"id":5120,"progress_pct":60,"status":"active", "...":"..."}}
POST/learners/bulkBulk import (max 500)

Creates or updates up to 500 learners and optionally enrols each in course_ids (max 20 per learner). Every row gets its own result, so one bad row never blocks the rest. Duplicate emails inside one request are flagged.

Request body
{"learners":[{"name":"Asha Verma","email":"asha@college.edu","mobile":"+919876543210","course_ids":[306]}]}
Example response
{"data":{"total":1,"ok":1,"failed":0,"learners_created":1,"learners_updated":0,"enrollments_created":1,"results":[{"index":0,"status":"created","email":"asha@college.edu","learner_id":991,"courses":[306]}]}}
GET/usage?from=&to=Usage and billable counts

Dates as DD/MM/YYYY or YYYY-MM-DD, max 400 days, default is the current month. Shows new and billable enrolments plus active learners and lesson opens per course.

Example response
{"data":{"period":{"from":"01/07/2026","to":"31/07/2026"},"totals":{"learners_total":240,"new_learners":60,"active_learners":131,"lesson_opens":4210,"new_enrollments":75,"billable_enrollments":75},"courses":[{"course_id":306,"title":"...","new_enrollments":40,"billable_enrollments":40,"active_learners":88,"lesson_opens":2500}]}}

Code samples

Set BASE=https://cosmosiq.ai/api/kiwan/v1 and KIWAN_KEY to your key.

Create learner + enrol (one call)

curl -X POST "$BASE/enrollments" \
  -H "Authorization: Bearer $KIWAN_KEY" \
  -H "Idempotency-Key: enr-2026-000123" \
  -H "Content-Type: application/json" \
  -d '{
    "course_id": 306,
    "learner": {
      "name": "Asha Verma",
      "email": "asha@college.edu",
      "mobile": "+919876543210",
      "consent_marketing": true,
      "institute_student_id": "BBA-2026-014"
    }
  }'
const BASE = "https://cosmosiq.ai/api/kiwan/v1";
const res = await fetch(`${BASE}/enrollments`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.KIWAN_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": "enr-2026-000123",
  },
  body: JSON.stringify({
    course_id: 306,
    learner: { name: "Asha Verma", email: "asha@college.edu", mobile: "+919876543210", consent_marketing: true },
  }),
});
const body = await res.json();
if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message} (request ${body.request_id})`);
console.log(body.data);
import os, requests
BASE = "https://cosmosiq.ai/api/kiwan/v1"
r = requests.post(
    f"{BASE}/enrollments",
    headers={"Authorization": f"Bearer {os.environ['KIWAN_KEY']}", "Idempotency-Key": "enr-2026-000123"},
    json={"course_id": 306,
          "learner": {"name": "Asha Verma", "email": "asha@college.edu",
                      "mobile": "+919876543210", "consent_marketing": True}},
    timeout=30,
)
body = r.json()
if not r.ok:
    raise RuntimeError(f"{body['error']['code']}: {body['error']['message']} (request {body['request_id']})")
print(body["data"])
<?php
$ch = curl_init("https://cosmosiq.ai/api/kiwan/v1/enrollments");
curl_setopt_array($ch, [
  CURLOPT_POST => true,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("KIWAN_KEY"),
    "Content-Type: application/json",
    "Idempotency-Key: enr-2026-000123",
  ],
  CURLOPT_POSTFIELDS => json_encode([
    "course_id" => 306,
    "learner" => ["name" => "Asha Verma", "email" => "asha@college.edu",
                  "mobile" => "+919876543210", "consent_marketing" => true],
  ]),
]);
$body = json_decode(curl_exec($ch), true);
print_r($body["data"] ?? $body["error"]);

Open a lesson (video or theory)

curl "$BASE/lessons/4521?email=student@example.com&format=both" \
  -H "Authorization: Bearer $KIWAN_KEY"
const url = `${BASE}/lessons/4521?email=${encodeURIComponent(email)}&format=both`;
const { data } = await (await fetch(url, { headers: { Authorization: `Bearer ${KEY}` } })).json();
if (data.type === "video") videoEl.src = data.video.stream_url;       // valid for 2 hours
else articleEl.innerHTML = data.theory.html;                           // already sanitised
r = requests.get(f"{BASE}/lessons/4521", params={"email": "asha@college.edu", "format": "both"},
                 headers={"Authorization": f"Bearer {KEY}"}, timeout=30)
d = r.json()["data"]
print(d["video"]["stream_url"] if d["type"] == "video" else d["theory"]["blocks"])
<?php
$ch = curl_init("https://cosmosiq.ai/api/kiwan/v1/lessons/4521?email=" . urlencode($email) . "&format=both");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("KIWAN_KEY")]]);
$d = json_decode(curl_exec($ch), true)["data"];
echo $d["type"] === "video" ? $d["video"]["stream_url"] : $d["theory"]["html"];

Practice questions (MCQ) and mind map

curl "$BASE/courses/306/mcq" -H "Authorization: Bearer $KIWAN_KEY"
curl "$BASE/mcq/4294?email=asha@college.edu" -H "Authorization: Bearer $KIWAN_KEY"
const get = (p) => fetch(`${BASE}${p}`, { headers: { Authorization: `Bearer ${KEY}` } }).then(r => r.json());
const { data: list } = await get("/courses/306/mcq");
const { data: set } = await get(`/mcq/${list.sets[0].id}?email=${encodeURIComponent(email)}`);
set.questions.forEach(q => console.log(q.number, q.text, q.options.map(o => o.key + ") " + o.text)));
const { data: lesson } = await get(`/lessons/37940?email=${encodeURIComponent(email)}`);
if (lesson.mindmap) mindmapEl.innerHTML = lesson.mindmap.svg;
h = {"Authorization": f"Bearer {KEY}"}
sets = requests.get(f"{BASE}/courses/306/mcq", headers=h, timeout=30).json()["data"]["sets"]
qs = requests.get(f"{BASE}/mcq/{sets[0]['id']}", params={"email": "asha@college.edu"}, headers=h, timeout=30).json()["data"]["questions"]
for q in qs:
    print(q["number"], q["text"], [o["key"] + ") " + o["text"] for o in q["options"]], q["correct_option"])
<?php
function kiwan_get($path) {
  $ch = curl_init("https://cosmosiq.ai/api/kiwan/v1" . $path);
  curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("KIWAN_KEY")]]);
  return json_decode(curl_exec($ch), true)["data"] ?? null;
}
$sets = kiwan_get("/courses/306/mcq")["sets"];
$set = kiwan_get("/mcq/" . $sets[0]["id"] . "?email=" . urlencode($email));
foreach ($set["questions"] as $q) echo $q["number"] . ". " . $q["text"] . "
";

Bulk import learners (up to 500)

curl -X POST "$BASE/learners/bulk" \
  -H "Authorization: Bearer $KIWAN_KEY" \
  -H "Idempotency-Key: batch-2026-07-01-a" \
  -H "Content-Type: application/json" \
  -d '{ "learners": [
    { "name": "Asha Verma",  "email": "asha@college.edu",  "mobile": "+919876543210", "course_ids": [306, 182] },
    { "name": "Rohan Mehta", "email": "rohan@college.edu", "mobile": "9123456789",    "course_ids": [306] }
  ]}'
rows = [{"name": n, "email": e, "mobile": m, "course_ids": [306]} for n, e, m in students]
for i in range(0, len(rows), 500):
    r = requests.post(f"{BASE}/learners/bulk", json={"learners": rows[i:i+500]},
                      headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": f"batch-{i}"}, timeout=120)
    res = r.json()["data"]
    for x in res["results"]:
        if x["status"] == "failed":
            print("row", x["index"], x["email"], x["error"]["code"], x["error"]["message"])
for (let i = 0; i < rows.length; i += 500) {
  const r = await fetch(`${BASE}/learners/bulk`, {
    method: "POST",
    headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json", "Idempotency-Key": `batch-${i}` },
    body: JSON.stringify({ learners: rows.slice(i, i + 500) }),
  });
  const { data } = await r.json();
  data.results.filter(x => x.status === "failed").forEach(x => console.log(x.index, x.email, x.error.code));
}
<?php
foreach (array_chunk($rows, 500) as $i => $chunk) {
  $ch = curl_init("https://cosmosiq.ai/api/kiwan/v1/learners/bulk");
  curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("KIWAN_KEY"), "Content-Type: application/json", "Idempotency-Key: batch-$i"],
    CURLOPT_POSTFIELDS => json_encode(["learners" => $chunk])]);
  $res = json_decode(curl_exec($ch), true)["data"];
}

SDK and libraries

Small, dependency-free client classes for the three most common stacks. Copy the file into your project: it adds the Authorization header, a fresh Idempotency-Key on every write, retries on 429/503 with back-off, and a typed error carrying the request_id. Official packages (npm, PyPI, Packagist) are not published yet; these single files are the supported starting point.

import { randomUUID } from "node:crypto";

export class KiwanError extends Error {
  constructor(status, error, requestId) {
    super(`${error.code}: ${error.message} (request ${requestId})`);
    Object.assign(this, { status, code: error.code, field: error.field, requestId });
  }
}

export class Kiwan {
  constructor({ key = process.env.KIWAN_KEY, base = "https://cosmosiq.ai/api/kiwan/v1", retries = 3 } = {}) {
    this.key = key;
    this.base = base;
    this.retries = retries;
  }

  async call(method, path, { query, body, idem } = {}) {
    const qs = query ? "?" + new URLSearchParams(query) : "";
    const headers = { Authorization: `Bearer ${this.key}` };
    if (body !== undefined) headers["Content-Type"] = "application/json";
    // one key per logical operation: a retry can never enrol twice
    if (method === "POST" || method === "PATCH") headers["Idempotency-Key"] = idem || randomUUID();
    for (let attempt = 0; ; attempt++) {
      const res = await fetch(this.base + path + qs, {
        method,
        headers,
        body: body === undefined ? undefined : JSON.stringify(body),
      });
      if ((res.status === 429 || res.status === 503) && attempt < this.retries) {
        const wait = Number(res.headers.get("Retry-After")) || 2 ** attempt;
        await new Promise((r) => setTimeout(r, wait * 1000));
        continue;
      }
      const json = await res.json();
      if (!res.ok) throw new KiwanError(res.status, json.error, json.request_id);
      return json.data;
    }
  }

  me() { return this.call("GET", "/me"); }
  courses() { return this.call("GET", "/courses"); }
  syllabus(courseId) { return this.call("GET", `/courses/${courseId}/syllabus`); }
  lesson(lessonId, email, format = "both") { return this.call("GET", `/lessons/${lessonId}`, { query: { email, format } }); }
  mcqSets(courseId) { return this.call("GET", `/courses/${courseId}/mcq`); }
  mcq(setId, email, answers = true) { return this.call("GET", `/mcq/${setId}`, { query: { email, answers } }); }
  enrol(courseId, learner) { return this.call("POST", "/enrollments", { body: { course_id: courseId, learner } }); }
  enrolments(query = {}) { return this.call("GET", "/enrollments", { query }); }
  reportProgress(email, courseId, pct) { return this.call("POST", "/progress", { body: { email, course_id: courseId, progress_pct: pct } }); }
  usage(from, to) { return this.call("GET", "/usage", { query: { from, to } }); }
}
import os
import time
import uuid

import requests


class KiwanError(Exception):
    def __init__(self, status, error, request_id):
        super().__init__(f"{error['code']}: {error['message']} (request {request_id})")
        self.status = status
        self.code = error["code"]
        self.field = error.get("field")
        self.request_id = request_id


class Kiwan:
    def __init__(self, key=None, base="https://cosmosiq.ai/api/kiwan/v1", retries=3, timeout=30):
        self.base, self.retries, self.timeout = base, retries, timeout
        self.http = requests.Session()
        self.http.headers["Authorization"] = "Bearer " + (key or os.environ["KIWAN_KEY"])

    def call(self, method, path, params=None, body=None, idem=None):
        headers = {}
        # one key per logical operation: a retry can never enrol twice
        if method in ("POST", "PATCH"):
            headers["Idempotency-Key"] = idem or str(uuid.uuid4())
        for attempt in range(self.retries + 1):
            r = self.http.request(method, self.base + path, params=params, json=body,
                                  headers=headers, timeout=self.timeout)
            if r.status_code in (429, 503) and attempt < self.retries:
                time.sleep(float(r.headers.get("Retry-After", 2 ** attempt)))
                continue
            data = r.json()
            if not r.ok:
                raise KiwanError(r.status_code, data["error"], data.get("request_id"))
            return data["data"]

    def me(self):
        return self.call("GET", "/me")

    def courses(self):
        return self.call("GET", "/courses")

    def syllabus(self, course_id):
        return self.call("GET", f"/courses/{course_id}/syllabus")

    def lesson(self, lesson_id, email, fmt="both"):
        return self.call("GET", f"/lessons/{lesson_id}", params={"email": email, "format": fmt})

    def mcq_sets(self, course_id):
        return self.call("GET", f"/courses/{course_id}/mcq")

    def mcq(self, set_id, email, answers=True):
        return self.call("GET", f"/mcq/{set_id}", params={"email": email, "answers": str(answers).lower()})

    def enrol(self, course_id, learner):
        return self.call("POST", "/enrollments", body={"course_id": course_id, "learner": learner})

    def enrolments(self, **filters):
        return self.call("GET", "/enrollments", params=filters)

    def report_progress(self, email, course_id, pct):
        return self.call("POST", "/progress", body={"email": email, "course_id": course_id, "progress_pct": pct})

    def usage(self, date_from=None, date_to=None):
        return self.call("GET", "/usage", params={"from": date_from, "to": date_to})
<?php
class KiwanException extends Exception {
    public $status; public $errorCode; public $requestId;
    public function __construct($status, $error, $requestId) {
        parent::__construct(($error["code"] ?? "error") . ": " . ($error["message"] ?? "") . " (request $requestId)");
        $this->status = $status; $this->errorCode = $error["code"] ?? null; $this->requestId = $requestId;
    }
}

class Kiwan {
    private $key; private $base; private $retries;

    public function __construct($key = null, $base = "https://cosmosiq.ai/api/kiwan/v1", $retries = 3) {
        $this->key = $key ?: getenv("KIWAN_KEY");
        $this->base = $base;
        $this->retries = $retries;
    }

    public function call($method, $path, $query = [], $body = null, $idem = null) {
        $url = $this->base . $path . ($query ? "?" . http_build_query($query) : "");
        $headers = ["Authorization: Bearer " . $this->key, "Accept: application/json"];
        if ($body !== null) $headers[] = "Content-Type: application/json";
        // one key per logical operation: a retry can never enrol twice
        if ($method === "POST" || $method === "PATCH") $headers[] = "Idempotency-Key: " . ($idem ?: bin2hex(random_bytes(16)));
        for ($attempt = 0; ; $attempt++) {
            $retryAfter = null;
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_CUSTOMREQUEST => $method,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_HEADERFUNCTION => function ($c, $h) use (&$retryAfter) {
                    if (stripos($h, "Retry-After:") === 0) $retryAfter = (int) trim(substr($h, 12));
                    return strlen($h);
                },
            ]);
            if ($body !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
            $raw = curl_exec($ch);
            $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if (($status === 429 || $status === 503) && $attempt < $this->retries) {
                sleep($retryAfter ?: 2 ** $attempt);
                continue;
            }
            $json = json_decode($raw, true);
            if ($status >= 400 || !isset($json["data"])) throw new KiwanException($status, $json["error"] ?? [], $json["request_id"] ?? null);
            return $json["data"];
        }
    }

    public function me() { return $this->call("GET", "/me"); }
    public function courses() { return $this->call("GET", "/courses"); }
    public function syllabus($courseId) { return $this->call("GET", "/courses/$courseId/syllabus"); }
    public function lesson($lessonId, $email, $format = "both") { return $this->call("GET", "/lessons/$lessonId", ["email" => $email, "format" => $format]); }
    public function mcqSets($courseId) { return $this->call("GET", "/courses/$courseId/mcq"); }
    public function mcq($setId, $email, $answers = true) { return $this->call("GET", "/mcq/$setId", ["email" => $email, "answers" => $answers ? "true" : "false"]); }
    public function enrol($courseId, $learner) { return $this->call("POST", "/enrollments", [], ["course_id" => $courseId, "learner" => $learner]); }
    public function enrolments($filters = []) { return $this->call("GET", "/enrollments", $filters); }
    public function reportProgress($email, $courseId, $pct) { return $this->call("POST", "/progress", [], ["email" => $email, "course_id" => $courseId, "progress_pct" => $pct]); }
}

Using the client

// Node.js (18+)
import { Kiwan } from "./kiwan.mjs";
const kiwan = new Kiwan();                       // reads KIWAN_KEY
const courses = await kiwan.courses();
await kiwan.enrol(306, { name: "Asha Verma", email: "student@example.com", mobile: "+919876543210" });
const lesson = await kiwan.lesson(4521, "student@example.com");

# Python (3.8+, requests)
from kiwan import Kiwan
kiwan = Kiwan()
kiwan.enrol(306, {"name": "Asha Verma", "email": "student@example.com", "mobile": "+919876543210"})
lesson = kiwan.lesson(4521, "student@example.com")

// PHP (7.4+, curl)
require "kiwan.php";
$kiwan = new Kiwan();
$kiwan->enrol(306, ["name" => "Asha Verma", "email" => "student@example.com", "mobile" => "+919876543210"]);
$lesson = $kiwan->lesson(4521, "student@example.com");

Postman collection

Import the ready-made collection, set the api_key variable to your sandbox key and run Who am I first.

Download the Postman collection

Webhooks (roadmap)

Status: planned, not available in API v1. There is no webhook endpoint to configure yet. Until it ships, use polling (below). The event list is shared so you can design for it.

Planned eventFires when
learner.enrolledA learner is enrolled in a course
progress.updatedProgress of an enrolment changes
course.completedAn enrolment reaches 100% / completed
enrollment.cancelledAn enrolment is cancelled
content.updatedContent of an assigned course is added or changed
access.suspendedAPI access is paused or the contract ends

What to do today: polling

API security and privacy

How the API is protected

Video URL access security

API audit logs and monitoring

Student data privacy: your responsibilities

Data retention and deletion

Troubleshooting

What you seeLikely causeWhat to do
401 missing_key / invalid_keyNo header, a typo, extra spaces, or a sandbox key used where a live key is expectedSend Authorization: Bearer <key> exactly; check the environment variable; test with GET /me
401 key_revoked / key_expiredThe key was revoked, or the rotation overlap has endedUse the newest key issued to you
403 origin_not_allowedThe call came from a browser page on a domain that is not registeredCall the API from your server, or ask CosmosIQ to register the domain
403 ip_not_allowedYour server IP is not on the allow-listSend the new IP to CosmosIQ
403 not_enrolledThe learner is not enrolled in the course of that lessonCall POST /enrollments first; check the email spelling
403 not_in_packageThe part (video, theory, MCQ, mind map) is not in your package for this courseCheck package in GET /courses; ask CosmosIQ to add the part
403 sandbox_content_lockedA sandbox key opened a lesson or set that is not a sampleUse the lessons marked "sample": true, or the live key
Video does not playThe link expired (2 hours), or the page is on an unregistered domainRequest a fresh stream_url when the lesson opens; check the page domain
422 validation_failedA field is missing or wrong; error.field names itFix the field; mobile must be 7-15 digits (a valid 10-digit number for +91)
422 idempotency_key_reusedThe same key was sent with a different bodyUse a new key for a new operation; reuse a key only when retrying the same request
429 rate_limitedMore than your requests-per-minute limitWait Retry-After seconds, back off, cache course and syllabus data
503 service_unavailableA temporary problem on our sideRetry with exponential back-off; quote the request_id if it persists

Errors

HTTPcodeMeaning
400invalid_jsonBody is not valid JSON.
401missing_keyNo API key was sent.
401invalid_keyThe key is not recognised.
401key_revokedThe key was revoked. Ask CosmosIQ for a new one.
401key_expiredThe key has passed its expiry date.
403institute_pausedYour access is paused. Existing learners keep their access on CosmosIQ.
403contract_endedThe contract period has ended. New API activity is stopped.
403contract_not_startedThe contract has not started yet.
403origin_not_allowedRequest came from a domain that is not registered for your institute.
403ip_not_allowedRequest came from an IP address that is not on your allow-list.
403course_not_assignedThis course is not assigned to your institute.
403not_enrolledThe learner is not enrolled in the course this lesson belongs to.
403sandbox_content_lockedSandbox keys can open only the sample content of each course (first video lesson, first theory lesson, first mind-map lesson, first MCQ set) and free-preview lessons.
403not_in_packageThis content (video, theory, MCQ or mind map) is not part of your package for this course.
404learner_not_foundNo learner with this email for your institute.
404enrollment_not_foundNo such enrolment.
404course_not_foundCourse not found for your institute.
404lesson_not_foundLesson not found, not published, or not part of your courses.
404mcq_set_not_foundMCQ set not found, not published, or not part of your courses.
409enrollment_cancelledThe enrolment is cancelled. Set it back to active first.
413payload_too_largeBody exceeds 1 MB.
422validation_failedA field is missing or invalid. error.field names it.
422too_many_itemsMore than 500 learners in a bulk request.
422idempotency_key_reusedThe same Idempotency-Key was used with a different body.
429rate_limitedToo many requests. Wait Retry-After seconds.
503service_unavailableTemporary problem on our side. Retry with back-off.

API changelog

Clarifications · November 2026
  • Sandbox, domain-check and assessment guidance clarified: the sandbox validates but does not save; domain checks depend on request headers; fetch MCQ sets with answers=false for learner screens and grade on your server.
  • New section: Content updates.
Developer & API Hub · November 2026
  • Documentation rebuilt as a Developer & API Hub: integration architecture, authentication guide, progress synchronization, webhooks roadmap, security and privacy, SDK files, troubleshooting, support and go-live.
  • Sandbox keys can now open sample content: the first video lesson, the first theory lesson, the first mind-map lesson and the first MCQ set of each assigned course. The syllabus marks them with "sample": true.
v1.0 · Initial release
  • Courses, syllabus, lessons (video, theory, mind map), MCQ sets, learners, enrolments, progress, bulk import (500) and usage.
  • Per-course content packages, sandbox and live keys, domain lock, idempotency and rate limits.

The API is versioned in the URL (/v1). Changes inside v1 are additive: new fields and endpoints may appear, existing ones are not removed or renamed. Ignore fields you do not recognise. A breaking change would ship as /v2 with advance notice and a parallel run of v1.

SLA and support

Onboarding and go-live

  1. Enquiry. Submit the access request on the KIWAN page (authorised person, verified email, contact, country, legal entity, website, organisation type and expected learners).
  2. Agreement and package. CosmosIQ confirms the courses and, for each course, the package (video, theory, MCQ, mind map).
  3. Institute set-up. Your institute is created, your domains are registered, and sandbox and live keys are issued.
  4. Build on sandbox. Use the Postman collection and SDK files; check sample lessons, syllabus and error handling.
  5. Test with live key. Enrol a few test learners, open lessons, report progress, and read GET /usage.
  6. Go live. Complete the checklist below, then open the courses to your learners.

Go-live checklist

CosmosIQ KIWAN API v1 · Developer & API Hub · Matriye Group, Pune. Quote the request_id when you contact support.