/healthHealth checkPublic, no key needed. Use it for uptime monitoring.
{"data":{"status":"ok","database":"ok","version":"1","time":"2026-07-01T09:30:00.000Z"},"request_id":"..."}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.
https://cosmosiq.ai/api/kiwan/v1sandbox key (for building and testing) and a live key (for production). Keep them on your server; never put a key in browser code.curl https://cosmosiq.ai/api/kiwan/v1/me -H "Authorization: Bearer YOUR_KEY"
GET /courses, then the syllabus with GET /courses/{id}/syllabus.POST /enrollments (name, email and mobile are compulsory for every learner).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}.POST /progress and read it with GET /enrollments (see Progress synchronization).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.
POST /enrollments once per learner and course.GET /lessons/{id}?email=... and passes the result to the page.POST /progress.GET /enrollments and GET /usage.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.
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.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.ip_not_allowed.GET /me shows your institute, environment, registered domains, courses assigned, contract end date and your rate limit.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.
kiwan_live_ab12cd34, are enough; never send the full key).401 key_revoked; the change takes effect within about a minute.GET /me.Sandbox key kiwan_sandbox_... | Live key kiwan_live_... | |
|---|---|---|
| Learners / enrolments / progress | Validated, not saved (response has "sandbox": true, "persisted": false) | Saved |
| Lessons | Sample 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 |
| MCQ | The set list works; the questions of the first set of each course can be opened | All sets, for enrolled learners, if MCQ is in your package |
| Billing | Never counted | Counted 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.
{"data": ..., "request_id": "..."}. Error: {"error": {"code", "message", "field"}, "request_id": "..."}. Quote the request_id (also in the X-Request-Id header) when contacting support.Idempotency-Key: <unique string> on every POST/PATCH. A retry with the same key and body returns the first result (header Idempotent-Replay: true) and never double-enrols. The same key with a different body returns idempotency_key_reused./me; higher limits on request). Headers X-RateLimit-Limit and X-RateLimit-Remaining are returned; on 429 wait Retry-After seconds.limit (max 200) and after; use next_after from the response until it is null.DD/MM/YYYY or YYYY-MM-DD. Timestamps in responses are ISO-8601 UTC.429 and 503 with exponential back-off. Do not retry other 4xx errors unchanged.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.
For every course assigned to you, CosmosIQ switches on the parts you have taken. The API returns only those parts.
| Part | What it is | Where you get it |
|---|---|---|
| Video | Lesson videos hosted by CosmosIQ | GET /lessons/{id} (video.stream_url) |
| Theory | Study notes: text, tables, key points, key terms, common mistakes, practice questions | GET /lessons/{id} (theory) |
| MCQ | Lesson quizzes and module tests (answers and explanations are available to your server) | GET /courses/{id}/mcq, GET /mcq/{set_id} |
| Mind map | A 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.
GET /lessons/{id}?email=learner@... from your server when the learner opens the lesson.video.stream_url to your player: <video controls src="STREAM_URL">. Seeking works (HTTP range requests).expires_at). Never store it; request a fresh one each time the lesson is opened.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>
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": "..." }GET /courses/{id}/mcq lists the sets (lesson quizzes and module tests).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.answers=false) and grade there. Show correct answers and explanations only after submission, or in a review mode you control.POST /progress.answers=false. The response has questions and options only.GET /mcq/{set_id}?email=... without answers=false, compares the choices with correct_option, and stores the score.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.
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.
| Direction | Call | What it does |
|---|---|---|
| You → CosmosIQ | POST /progress | Send progress_pct (0-100) for an email and course. 100 marks the enrolment completed and sets completed_at. |
| CosmosIQ → you | GET /enrollments?email=&course_id=&status= | Returns status, progress_pct, enrolled_at, first_accessed_at, last_accessed_at, completed_at. Paginated with after. |
| Status | PATCH /enrollments/{id} | Set active, cancelled or completed. |
| Reconciliation | GET /usage?from=&to= | Enrolled, billable and active learners and lesson opens per course. |
Idempotency-Key per report so retries are safe.GET /enrollments?status=active and compares it with your own records. Treat your LMS as the source of truth for in-LMS activity.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 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.
GET /courses and GET /courses/{id}/syllabus on a schedule (for example nightly) and compare counts and titles with your copy.GET /courses always shows the current list and the package per course.institute_paused / contract_ended) and video links on your site stop working.PATCH status cancelled) stops lesson access through the API for that learner. Setting it back to active restores it.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.
/healthHealth checkPublic, no key needed. Use it for uptime monitoring.
{"data":{"status":"ok","database":"ok","version":"1","time":"2026-07-01T09:30:00.000Z"},"request_id":"..."}/meWho am IShows your institute, environment (live or sandbox), registered domains, contract end date and your rate limit.
{"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}}/coursesList your coursesOnly 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).
{"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://..."}]}}/courses/{course_id}/syllabusCourse syllabusModules 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.
{"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}]}]}}/lessons/{lesson_id}?email=&format=Open a lessonLive 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.
{"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"}}}/courses/{course_id}/mcqList MCQ setsNeeds MCQ in your package for the course. Returns lesson quizzes and module tests with question counts, time limit and passing score.
{"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}]}}/mcq/{set_id}?email=&answers=Get the questions of an MCQ setLive 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.
{"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":"..."}]}}/learnersCreate or update a learnername, 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.
{"name":"Asha Verma","email":"asha@college.edu","mobile":"+919876543210","consent_marketing":true,"institute_student_id":"BBA-2026-014"}{"data":{"created":true,"id":991,"name":"Asha Verma","email":"asha@college.edu","mobile":"+919876543210","consent_marketing":true,"institute_student_id":"BBA-2026-014"}}/learners?email= | ?limit=&after=Get or list learnersWith ?email= returns one learner. Without it, returns a page (limit up to 200) and next_after for the next page.
{"data":{"items":[{"id":991,"name":"...","email":"..."}],"next_after":null}}/enrollmentsEnrol a learner in a courseSend 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).
{"course_id":306,"email":"asha@college.edu"}{"data":{"created":true,"reactivated":false,"learner_created":false,"id":5120,"email":"asha@college.edu","course_id":306,"status":"active","progress_pct":0}}/enrollments?email=&course_id=&status=&limit=&after=List enrolmentsFilter by learner, course or status (active, cancelled, completed). Paginated.
{"data":{"items":[{"id":5120,"email":"...","course_id":306,"status":"active","progress_pct":42.5,"first_accessed_at":"...","last_accessed_at":"..."}],"next_after":null}}/enrollments/{id}Change enrolment statusstatus = active | cancelled | completed.
{"status":"cancelled"}{"data":{"id":5120,"status":"cancelled", "...":"..."}}/progressReport learner progressSend progress_pct (0-100) for a learner and course. 100 marks the enrolment completed.
{"email":"asha@college.edu","course_id":306,"progress_pct":60}{"data":{"id":5120,"progress_pct":60,"status":"active", "...":"..."}}/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.
{"learners":[{"name":"Asha Verma","email":"asha@college.edu","mobile":"+919876543210","course_ids":[306]}]}{"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]}]}}/usage?from=&to=Usage and billable countsDates 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.
{"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}]}}Set BASE=https://cosmosiq.ai/api/kiwan/v1 and KIWAN_KEY to your key.
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"]);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 sanitisedr = 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"];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"] . "
";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"];
}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]); }
}// 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");Import the ready-made collection, set the api_key variable to your sandbox key and run Who am I first.
Download the Postman collection
base_url, api_key, course_id, lesson_id, mcq_set_id, learner_email, enrollment_id.Idempotency-Key ({{$guid}}).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 event | Fires when |
|---|---|
learner.enrolled | A learner is enrolled in a course |
progress.updated | Progress of an enrolment changes |
course.completed | An enrolment reaches 100% / completed |
enrollment.cancelled | An enrolment is cancelled |
content.updated | Content of an assigned course is added or changed |
access.suspended | API access is paused or the contract ends |
GET /enrollments?status=active (or completed) every few minutes to hourly and compare with your records.GET /courses (counts and content_status) daily.GET /me or GET /health; a paused or ended contract returns institute_paused / contract_ended on any call.Origin header of browser requests (server-to-server calls normally send none); the IP allow-list restricts which server addresses may call the API with your key. See the authentication guide./me and in the X-RateLimit-* headers; 429 carries Retry-After. Ask for a higher limit if your traffic needs it."persisted": false), are never billed, and open sample content only. Sandbox and live run on the same service; the difference is enforced per key.stream_url is signed by CosmosIQ and tied to your institute; it cannot be edited or reused for another institute.Origin or Referer header. Treat this as a safeguard, not DRM: the signature and the 2-hour expiry are the main protection. Pausing or ending the contract stops playback.request_id of every call, alert on repeated 401, 403 and 429, and watch X-RateLimit-Remaining.consent_marketing to true only when the learner has agreed to receive CosmosIQ updates.| What you see | Likely cause | What to do |
|---|---|---|
401 missing_key / invalid_key | No header, a typo, extra spaces, or a sandbox key used where a live key is expected | Send Authorization: Bearer <key> exactly; check the environment variable; test with GET /me |
401 key_revoked / key_expired | The key was revoked, or the rotation overlap has ended | Use the newest key issued to you |
403 origin_not_allowed | The call came from a browser page on a domain that is not registered | Call the API from your server, or ask CosmosIQ to register the domain |
403 ip_not_allowed | Your server IP is not on the allow-list | Send the new IP to CosmosIQ |
403 not_enrolled | The learner is not enrolled in the course of that lesson | Call POST /enrollments first; check the email spelling |
403 not_in_package | The part (video, theory, MCQ, mind map) is not in your package for this course | Check package in GET /courses; ask CosmosIQ to add the part |
403 sandbox_content_locked | A sandbox key opened a lesson or set that is not a sample | Use the lessons marked "sample": true, or the live key |
| Video does not play | The link expired (2 hours), or the page is on an unregistered domain | Request a fresh stream_url when the lesson opens; check the page domain |
422 validation_failed | A field is missing or wrong; error.field names it | Fix the field; mobile must be 7-15 digits (a valid 10-digit number for +91) |
422 idempotency_key_reused | The same key was sent with a different body | Use a new key for a new operation; reuse a key only when retrying the same request |
429 rate_limited | More than your requests-per-minute limit | Wait Retry-After seconds, back off, cache course and syllabus data |
503 service_unavailable | A temporary problem on our side | Retry with exponential back-off; quote the request_id if it persists |
| HTTP | code | Meaning |
|---|---|---|
| 400 | invalid_json | Body is not valid JSON. |
| 401 | missing_key | No API key was sent. |
| 401 | invalid_key | The key is not recognised. |
| 401 | key_revoked | The key was revoked. Ask CosmosIQ for a new one. |
| 401 | key_expired | The key has passed its expiry date. |
| 403 | institute_paused | Your access is paused. Existing learners keep their access on CosmosIQ. |
| 403 | contract_ended | The contract period has ended. New API activity is stopped. |
| 403 | contract_not_started | The contract has not started yet. |
| 403 | origin_not_allowed | Request came from a domain that is not registered for your institute. |
| 403 | ip_not_allowed | Request came from an IP address that is not on your allow-list. |
| 403 | course_not_assigned | This course is not assigned to your institute. |
| 403 | not_enrolled | The learner is not enrolled in the course this lesson belongs to. |
| 403 | sandbox_content_locked | Sandbox 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. |
| 403 | not_in_package | This content (video, theory, MCQ or mind map) is not part of your package for this course. |
| 404 | learner_not_found | No learner with this email for your institute. |
| 404 | enrollment_not_found | No such enrolment. |
| 404 | course_not_found | Course not found for your institute. |
| 404 | lesson_not_found | Lesson not found, not published, or not part of your courses. |
| 404 | mcq_set_not_found | MCQ set not found, not published, or not part of your courses. |
| 409 | enrollment_cancelled | The enrolment is cancelled. Set it back to active first. |
| 413 | payload_too_large | Body exceeds 1 MB. |
| 422 | validation_failed | A field is missing or invalid. error.field names it. |
| 422 | too_many_items | More than 500 learners in a bulk request. |
| 422 | idempotency_key_reused | The same Idempotency-Key was used with a different body. |
| 429 | rate_limited | Too many requests. Wait Retry-After seconds. |
| 503 | service_unavailable | Temporary problem on our side. Retry with back-off. |
answers=false for learner screens and grade on your server."sample": true.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.
GET /health is public and needs no key; poll it for uptime checks. It reports the API and database status.request_id, the time, the endpoint and the error code.503 with Retry-After if a short interruption happens.GET /usage.Idempotency-Key.request_id is logged.not_in_package is handled.consent_marketing value.CosmosIQ KIWAN API v1 · Developer & API Hub · Matriye Group, Pune. Quote the request_id when you contact support.