Docs Start here
Quickstart
Put courses in your own app and track your users' progress. No backend to build.
No BS LMS is the backend for learning: courses, lessons, quizzes, progress and certificates. You make the courses in the admin, and your app talks to us over a simple API to show them and track progress.
1. Build your content#
Sign in to the admin and create a course: add sections, lessons and quizzes, then press Publish. Nothing to code. Each course has an address (a short name like safety-101, shown in the course list) that you’ll use below.
2. Create an API key#
In the admin, open Developers, press Create key, choose Read and change, and copy the key. It is shown once.
Your key is a secret, like a password. Keep it on your server (an environment variable or your secrets manager), never in a browser, a mobile app or git. Your server also needs your API address, which is the URL you use to reach us.
LMS_URL=https://api.nobslms.app
LMS_KEY=nbl_xxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
3. Start a learner, from your server#
When one of your users opens a course, ask us to start them. Send who they are (use your own id for them, so the same person always lands on the same learner) and which courses they should have. We create them, enrol them, and send back a token your app uses to show them their course. It’s safe to call every time.
const LMS_URL = process.env.LMS_URL
const LMS_KEY = process.env.LMS_KEY
async function lms(method, path, body) {
const res = await fetch(`${LMS_URL}/api/v1${path}`, {
method,
headers: { 'X-API-Key': LMS_KEY, 'Content-Type': 'application/json' },
body: body && JSON.stringify(body),
})
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`)
return res.json()
}
// Call this when one of your users opens a course.
export function startLearner(user, courses) {
return lms('POST', `/learners/${user.id}/session`, {
email: user.email, givenName: user.firstName, familyName: user.lastName, courses,
}) // { learnerId, accessToken, expiresInSeconds }
}const LMS_URL = process.env.LMS_URL!
const LMS_KEY = process.env.LMS_KEY!
async function lms<T = any>(method: string, path: string, body?: unknown): Promise<T> {
const res = await fetch(`${LMS_URL}/api/v1${path}`, {
method,
headers: { 'X-API-Key': LMS_KEY, 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : undefined,
})
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`)
return res.json() as Promise<T>
}
interface AppUser { id: string; email: string; firstName: string; lastName: string }
interface LearnerSession { learnerId: string; accessToken: string; expiresInSeconds: number }
// Call this when one of your users opens a course.
export function startLearner(user: AppUser, courses: string[]) {
return lms<LearnerSession>('POST', `/learners/${user.id}/session`, {
email: user.email, givenName: user.firstName, familyName: user.lastName, courses,
})
}import os
import requests
LMS = os.environ["LMS_URL"] + "/api/v1"
HEADERS = {"X-API-Key": os.environ["LMS_KEY"]}
def lms(method, path, body=None):
res = requests.request(method, LMS + path, headers=HEADERS, json=body, timeout=10)
res.raise_for_status()
return res.json()
def start_learner(user, courses):
"""Call this when one of your users opens a course."""
return lms("POST", f"/learners/{user['id']}/session", {
"email": user["email"], "givenName": user["first_name"], "familyName": user["last_name"], "courses": courses,
}) # {"learnerId": ..., "accessToken": ..., "expiresInSeconds": ...}import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
public class Lms {
static final String URL = System.getenv("LMS_URL");
static final String KEY = System.getenv("LMS_KEY");
static final HttpClient http = HttpClient.newHttpClient();
static final ObjectMapper json = new ObjectMapper();
static JsonNode call(String method, String path, Object body) throws Exception {
var request = HttpRequest.newBuilder(URI.create(URL + "/api/v1" + path))
.header("X-API-Key", KEY)
.header("Content-Type", "application/json")
.method(method, body == null
? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body)))
.build();
var response = http.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 300) throw new IllegalStateException(response.statusCode() + " " + response.body());
return json.readTree(response.body());
}
/** Call this when one of your users opens a course. Returns learnerId, accessToken, expiresInSeconds. */
public static JsonNode startLearner(String userId, String email, String firstName, String lastName, List<String> courses)
throws Exception {
return call("POST", "/learners/" + userId + "/session",
Map.of("email", email, "givenName", firstName, "familyName", lastName, "courses", courses));
}
}# app/services/lms.rb (Rails)
require "net/http"
require "json"
module Lms
URL = ENV.fetch("LMS_URL")
KEY = ENV.fetch("LMS_KEY")
def self.call(method, path, body = nil)
uri = URI("#{URL}/api/v1#{path}")
request = Net::HTTP.const_get(method.capitalize).new(uri, "X-API-Key" => KEY, "Content-Type" => "application/json")
request.body = body.to_json if body
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
raise "#{response.code} #{response.body}" unless response.is_a?(Net::HTTPSuccess)
JSON.parse(response.body)
end
# Call this when one of your users opens a course: Lms.start_learner(current_user, ["safety-101"])
def self.start_learner(user, courses)
call("POST", "/learners/#{user.id}/session",
email: user.email, givenName: user.first_name, familyName: user.last_name, courses: courses)
end
end<?php
function lms(string $method, string $path, ?array $body = null): array
{
$options = [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('LMS_KEY'), 'Content-Type: application/json'],
];
if ($body !== null) {
$options[CURLOPT_POSTFIELDS] = json_encode($body);
}
$ch = curl_init(getenv('LMS_URL') . "/api/v1$path");
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status >= 300) {
throw new RuntimeException("$status $response");
}
return json_decode($response, true);
}
// Call this when one of your users opens a course.
function startLearner(array $user, array $courses): array
{
return lms('POST', "/learners/{$user['id']}/session", [
'email' => $user['email'], 'givenName' => $user['first_name'], 'familyName' => $user['last_name'], 'courses' => $courses,
]);
}package lms
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func call(method, path string, body, out any) error {
var payload io.Reader
if body != nil {
b, _ := json.Marshal(body)
payload = bytes.NewReader(b)
}
req, _ := http.NewRequest(method, os.Getenv("LMS_URL")+"/api/v1"+path, payload)
req.Header.Set("X-API-Key", os.Getenv("LMS_KEY"))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
data, _ := io.ReadAll(res.Body)
if res.StatusCode >= 300 {
return fmt.Errorf("%d %s", res.StatusCode, data)
}
return json.Unmarshal(data, out)
}
type Session struct{ LearnerID, AccessToken string }
// StartLearner: call this when one of your users opens a course.
func StartLearner(userID, email, firstName, lastName string, courses []string) (Session, error) {
var s Session
err := call("POST", "/learners/"+userID+"/session", map[string]any{
"email": email, "givenName": firstName, "familyName": lastName, "courses": courses,
}, &s)
return s, err
}curl -X POST "$LMS_URL/api/v1/learners/user-42/session" \
-H "X-API-Key: $LMS_KEY" -H "Content-Type: application/json" \
-d '{"email":"ada@customer.example","givenName":"Ada","familyName":"Lovelace","courses":["safety-101"]}'You get back learnerId and an accessToken. Give the token to your front end. It can only act as that one person and it lasts an hour; call again for a fresh one.
4. Show the course in your app#
Now the person’s own experience, using the token from step 3: their courses, the lesson menu, a lesson’s content, progress, and finishing. In a single-page app these calls run in the browser. If you render pages on your server, run them there. Add this to the same file as step 3.
async function asLearner(token, method, path, body) {
const res = await fetch(`${LMS_URL}/api/v1${path}`, {
method,
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: body && JSON.stringify(body),
})
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`)
return res.status === 204 ? null : res.json()
}
// Show the course, open the first lesson, report progress, finish it.
export async function learn(token) {
const [{ id: enrollment }] = await asLearner(token, 'GET', '/me/enrollments') // their courses
const course = await asLearner(token, 'GET', `/me/enrollments/${enrollment}/course`) // the menu: sections, lessons, done or locked
const lessonId = course.modules[0].lessons[0].id
const base = `/me/enrollments/${enrollment}/lessons/${lessonId}`
const lesson = await asLearner(token, 'GET', base) // content blocks to render; starts the lesson
await asLearner(token, 'PUT', `${base}/progress`, { secondsSpent: 30, resumeState: { position: 142 } }) // heartbeat
await asLearner(token, 'POST', `${base}/complete`)
return { course, lesson }
}async function asLearner<T = any>(token: string, method: string, path: string, body?: unknown): Promise<T> {
const res = await fetch(`${LMS_URL}/api/v1${path}`, {
method,
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : undefined,
})
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`)
return (res.status === 204 ? null : await res.json()) as T
}
// Show the course, open the first lesson, report progress, finish it.
export async function learn(token: string) {
const [{ id: enrollment }] = await asLearner<{ id: string }[]>(token, 'GET', '/me/enrollments') // their courses
const course = await asLearner(token, 'GET', `/me/enrollments/${enrollment}/course`) // the menu: sections, lessons, done or locked
const lessonId: string = course.modules[0].lessons[0].id
const base = `/me/enrollments/${enrollment}/lessons/${lessonId}`
const lesson = await asLearner(token, 'GET', base) // content blocks to render; starts the lesson
await asLearner(token, 'PUT', `${base}/progress`, { secondsSpent: 30, resumeState: { position: 142 } }) // heartbeat
await asLearner(token, 'POST', `${base}/complete`)
return { course, lesson }
}def as_learner(token, method, path, body=None):
res = requests.request(method, LMS + path, headers={"Authorization": f"Bearer {token}"}, json=body, timeout=10)
res.raise_for_status()
return res.json() if res.content else None
def learn(token):
"""Show the course, open the first lesson, report progress, finish it."""
enrollment = as_learner(token, "GET", "/me/enrollments")[0]["id"] # their courses
course = as_learner(token, "GET", f"/me/enrollments/{enrollment}/course") # the menu: sections, lessons, done or locked
lesson_id = course["modules"][0]["lessons"][0]["id"]
base = f"/me/enrollments/{enrollment}/lessons/{lesson_id}"
lesson = as_learner(token, "GET", base) # content blocks to render; starts the lesson
as_learner(token, "PUT", base + "/progress", {"secondsSpent": 30, "resumeState": {"position": 142}}) # heartbeat
as_learner(token, "POST", base + "/complete")
return course, lesson static JsonNode asLearner(String token, String method, String path, Object body) throws Exception {
var request = HttpRequest.newBuilder(URI.create(URL + "/api/v1" + path))
.header("Authorization", "Bearer " + token)
.header("Content-Type", "application/json")
.method(method, body == null
? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body)))
.build();
var response = http.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 300) throw new IllegalStateException(response.statusCode() + " " + response.body());
return json.readTree(response.body());
}
/** Show the course, open the first lesson, report progress, finish it. Returns the lesson's content. */
public static JsonNode learn(String token) throws Exception {
String enrollment = asLearner(token, "GET", "/me/enrollments", null).get(0).get("id").asText(); // their courses
JsonNode course = asLearner(token, "GET", "/me/enrollments/" + enrollment + "/course", null); // the menu
String lessonId = course.get("modules").get(0).get("lessons").get(0).get("id").asText();
String base = "/me/enrollments/" + enrollment + "/lessons/" + lessonId;
JsonNode lesson = asLearner(token, "GET", base, null); // content blocks; starts the lesson
asLearner(token, "PUT", base + "/progress", Map.of("secondsSpent", 30, "resumeState", Map.of("position", 142)));
asLearner(token, "POST", base + "/complete", null);
return lesson;
} def self.as_learner(token, method, path, body = nil)
uri = URI("#{URL}/api/v1#{path}")
request = Net::HTTP.const_get(method.capitalize).new(uri, "Authorization" => "Bearer #{token}", "Content-Type" => "application/json")
request.body = body.to_json if body
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
raise "#{response.code} #{response.body}" unless response.is_a?(Net::HTTPSuccess)
response.body.to_s.empty? ? nil : JSON.parse(response.body)
end
# Show the course, open the first lesson, report progress, finish it. Returns the lesson's content.
def self.learn(token)
enrollment = as_learner(token, "GET", "/me/enrollments").first["id"] # their courses
course = as_learner(token, "GET", "/me/enrollments/#{enrollment}/course") # the menu: sections, lessons, done or locked
lesson_id = course["modules"][0]["lessons"][0]["id"]
base = "/me/enrollments/#{enrollment}/lessons/#{lesson_id}"
lesson = as_learner(token, "GET", base) # content blocks to render; starts the lesson
as_learner(token, "PUT", "#{base}/progress", secondsSpent: 30, resumeState: { position: 142 })
as_learner(token, "POST", "#{base}/complete")
lesson
endfunction asLearner(string $token, string $method, string $path, ?array $body = null): ?array
{
$options = [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer $token", 'Content-Type: application/json'],
];
if ($body !== null) {
$options[CURLOPT_POSTFIELDS] = json_encode($body);
}
$ch = curl_init(getenv('LMS_URL') . "/api/v1$path");
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status >= 300) {
throw new RuntimeException("$status $response");
}
return $response === '' ? null : json_decode($response, true);
}
// Show the course, open the first lesson, report progress, finish it.
function learn(string $token): array
{
$enrollment = asLearner($token, 'GET', '/me/enrollments')[0]['id']; // their courses
$course = asLearner($token, 'GET', "/me/enrollments/$enrollment/course"); // the menu: sections, lessons, done or locked
$base = "/me/enrollments/$enrollment/lessons/{$course['modules'][0]['lessons'][0]['id']}";
$lesson = asLearner($token, 'GET', $base); // content blocks to render; starts the lesson
asLearner($token, 'PUT', "$base/progress", ['secondsSpent' => 30, 'resumeState' => ['position' => 142]]);
asLearner($token, 'POST', "$base/complete");
return $lesson;
}func asLearner(token, method, path string, body, out any) error {
var payload io.Reader
if body != nil {
b, _ := json.Marshal(body)
payload = bytes.NewReader(b)
}
req, _ := http.NewRequest(method, os.Getenv("LMS_URL")+"/api/v1"+path, payload)
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
data, _ := io.ReadAll(res.Body)
if res.StatusCode >= 300 {
return fmt.Errorf("%d %s", res.StatusCode, data)
}
if out != nil && len(data) > 0 {
return json.Unmarshal(data, out)
}
return nil
}
type Lesson struct {
Title string
Blocks []map[string]any
}
// Learn shows the course, opens the first lesson, reports progress and finishes it.
func Learn(token string) (Lesson, error) {
var enrollments []struct{ ID string }
if err := asLearner(token, "GET", "/me/enrollments", nil, &enrollments); err != nil { // their courses
return Lesson{}, err
}
enrollment := enrollments[0].ID
var course struct{ Modules []struct{ Lessons []struct{ ID string } } } // the menu: sections, lessons, done or locked
if err := asLearner(token, "GET", "/me/enrollments/"+enrollment+"/course", nil, &course); err != nil {
return Lesson{}, err
}
base := "/me/enrollments/" + enrollment + "/lessons/" + course.Modules[0].Lessons[0].ID
var lesson Lesson // content blocks to render; opening starts the lesson
if err := asLearner(token, "GET", base, nil, &lesson); err != nil {
return Lesson{}, err
}
progress := map[string]any{"secondsSpent": 30, "resumeState": map[string]int{"position": 142}}
if err := asLearner(token, "PUT", base+"/progress", progress, nil); err != nil {
return Lesson{}, err
}
return lesson, asLearner(token, "POST", base+"/complete", nil, nil)
}LMS_TOKEN=eyJ... # the accessToken from step 3
H=(-H "Authorization: Bearer $LMS_TOKEN" -H "Content-Type: application/json")
ENROLLMENT=$(curl -s "$LMS_URL/api/v1/me/enrollments" "${H[@]}" | jq -r '.[0].id') # their courses
curl -s "$LMS_URL/api/v1/me/enrollments/$ENROLLMENT/course" "${H[@]}" > course.json # the menu: sections, lessons, done or locked
LESSON=$(jq -r '.modules[0].lessons[0].id' course.json)
BASE="$LMS_URL/api/v1/me/enrollments/$ENROLLMENT/lessons/$LESSON"
curl -s "$BASE" "${H[@]}" # content blocks to render; starts the lesson
curl -s -X PUT "$BASE/progress" "${H[@]}" -d '{"secondsSpent":30,"resumeState":{"position":142}}'
curl -s -X POST "$BASE/complete" "${H[@]}"A quiz#
A quiz is a block inside a lesson. Start an attempt, collect answers, submit. Questions arrive without their answers. Every question type has its own answer shape: Quizzes and questions.
export async function takeQuiz(token) {
const [{ id: enrollment }] = await asLearner(token, 'GET', '/me/enrollments')
const course = await asLearner(token, 'GET', `/me/enrollments/${enrollment}/course`)
const quizLesson = course.modules.flatMap((m) => m.lessons).find((l) => l.completionMode === 'ASSESSMENT_PASSED')
const { blocks } = await asLearner(token, 'GET', `/me/enrollments/${enrollment}/lessons/${quizLesson.id}`)
const assessment = blocks.find((b) => b.type === 'ASSESSMENT').assessment
const attempt = await asLearner(token, 'POST', `/me/enrollments/${enrollment}/assessments/${assessment.id}/attempts`)
// render attempt.questions, then send one response per question in the shape its type expects
const answers = [{ questionId: attempt.questions[0].id, response: { value: false } }]
return asLearner(token, 'POST', `/me/enrollments/${enrollment}/attempts/${attempt.id}/submit`, { answers })
// { status: 'GRADED', passed: true, scorePercent: 100 }
}export async function takeQuiz(token: string) {
const [{ id: enrollment }] = await asLearner<{ id: string }[]>(token, 'GET', '/me/enrollments')
const course = await asLearner(token, 'GET', `/me/enrollments/${enrollment}/course`)
const quizLesson = course.modules.flatMap((m: any) => m.lessons).find((l: any) => l.completionMode === 'ASSESSMENT_PASSED')
const { blocks } = await asLearner(token, 'GET', `/me/enrollments/${enrollment}/lessons/${quizLesson.id}`)
const assessment = blocks.find((b: any) => b.type === 'ASSESSMENT').assessment
const attempt = await asLearner(token, 'POST', `/me/enrollments/${enrollment}/assessments/${assessment.id}/attempts`)
// render attempt.questions, then send one response per question in the shape its type expects
const answers = [{ questionId: attempt.questions[0].id, response: { value: false } }]
return asLearner<{ status: string; passed: boolean; scorePercent: number }>(
token, 'POST', `/me/enrollments/${enrollment}/attempts/${attempt.id}/submit`, { answers })
}def take_quiz(token):
enrollment = as_learner(token, "GET", "/me/enrollments")[0]["id"]
course = as_learner(token, "GET", f"/me/enrollments/{enrollment}/course")
quiz_lesson = next(l for m in course["modules"] for l in m["lessons"] if l["completionMode"] == "ASSESSMENT_PASSED")
blocks = as_learner(token, "GET", f"/me/enrollments/{enrollment}/lessons/{quiz_lesson['id']}")["blocks"]
assessment = next(b for b in blocks if b["type"] == "ASSESSMENT")["assessment"]
attempt = as_learner(token, "POST", f"/me/enrollments/{enrollment}/assessments/{assessment['id']}/attempts")
# render attempt["questions"], then send one response per question in the shape its type expects
answers = [{"questionId": attempt["questions"][0]["id"], "response": {"value": False}}]
return as_learner(token, "POST", f"/me/enrollments/{enrollment}/attempts/{attempt['id']}/submit", {"answers": answers})
# {"status": "GRADED", "passed": True, "scorePercent": 100} public static JsonNode takeQuiz(String token) throws Exception {
String enrollment = asLearner(token, "GET", "/me/enrollments", null).get(0).get("id").asText();
JsonNode course = asLearner(token, "GET", "/me/enrollments/" + enrollment + "/course", null);
String quizLessonId = null;
for (JsonNode m : course.get("modules")) {
for (JsonNode l : m.get("lessons")) {
if (l.get("completionMode").asText().equals("ASSESSMENT_PASSED")) quizLessonId = l.get("id").asText();
}
}
String assessment = null;
for (JsonNode b : asLearner(token, "GET", "/me/enrollments/" + enrollment + "/lessons/" + quizLessonId, null).get("blocks")) {
if (b.get("type").asText().equals("ASSESSMENT")) assessment = b.get("assessment").get("id").asText();
}
JsonNode attempt = asLearner(token, "POST", "/me/enrollments/" + enrollment + "/assessments/" + assessment + "/attempts", null);
// render attempt.get("questions"), then send one response per question in the shape its type expects
var answers = List.of(Map.of("questionId", attempt.get("questions").get(0).get("id").asText(), "response", Map.of("value", false)));
return asLearner(token, "POST", "/me/enrollments/" + enrollment + "/attempts/" + attempt.get("id").asText() + "/submit",
Map.of("answers", answers)); // status GRADED, passed true, scorePercent 100
} def self.take_quiz(token)
enrollment = as_learner(token, "GET", "/me/enrollments").first["id"]
course = as_learner(token, "GET", "/me/enrollments/#{enrollment}/course")
quiz_lesson = course["modules"].flat_map { |m| m["lessons"] }.find { |l| l["completionMode"] == "ASSESSMENT_PASSED" }
blocks = as_learner(token, "GET", "/me/enrollments/#{enrollment}/lessons/#{quiz_lesson['id']}")["blocks"]
assessment = blocks.find { |b| b["type"] == "ASSESSMENT" }["assessment"]
attempt = as_learner(token, "POST", "/me/enrollments/#{enrollment}/assessments/#{assessment['id']}/attempts")
# render attempt["questions"], then send one response per question in the shape its type expects
answers = [{ questionId: attempt["questions"][0]["id"], response: { value: false } }]
as_learner(token, "POST", "/me/enrollments/#{enrollment}/attempts/#{attempt['id']}/submit", answers: answers)
# { "status" => "GRADED", "passed" => true, "scorePercent" => 100 }
endfunction takeQuiz(string $token): array
{
$enrollment = asLearner($token, 'GET', '/me/enrollments')[0]['id'];
$course = asLearner($token, 'GET', "/me/enrollments/$enrollment/course");
$lessons = array_merge(...array_column($course['modules'], 'lessons'));
$quizLesson = current(array_filter($lessons, fn ($l) => $l['completionMode'] === 'ASSESSMENT_PASSED'));
$blocks = asLearner($token, 'GET', "/me/enrollments/$enrollment/lessons/{$quizLesson['id']}")['blocks'];
$assessment = current(array_filter($blocks, fn ($b) => $b['type'] === 'ASSESSMENT'))['assessment'];
$attempt = asLearner($token, 'POST', "/me/enrollments/$enrollment/assessments/{$assessment['id']}/attempts");
// render $attempt['questions'], then send one response per question in the shape its type expects
$answers = [['questionId' => $attempt['questions'][0]['id'], 'response' => ['value' => false]]];
return asLearner($token, 'POST', "/me/enrollments/$enrollment/attempts/{$attempt['id']}/submit", ['answers' => $answers]);
// ['status' => 'GRADED', 'passed' => true, 'scorePercent' => 100]
}type QuizResult struct {
Status string
Passed bool
ScorePercent float64
}
func TakeQuiz(token string) (QuizResult, error) {
var enrollments []struct{ ID string }
if err := asLearner(token, "GET", "/me/enrollments", nil, &enrollments); err != nil {
return QuizResult{}, err
}
enrollment := enrollments[0].ID
var course struct{ Modules []struct{ Lessons []struct{ ID, CompletionMode string } } }
if err := asLearner(token, "GET", "/me/enrollments/"+enrollment+"/course", nil, &course); err != nil {
return QuizResult{}, err
}
var quizLesson string
for _, m := range course.Modules {
for _, l := range m.Lessons {
if l.CompletionMode == "ASSESSMENT_PASSED" {
quizLesson = l.ID
}
}
}
var lesson struct{ Blocks []struct{ Type string; Assessment struct{ ID string } } }
if err := asLearner(token, "GET", "/me/enrollments/"+enrollment+"/lessons/"+quizLesson, nil, &lesson); err != nil {
return QuizResult{}, err
}
var assessment string
for _, b := range lesson.Blocks {
if b.Type == "ASSESSMENT" {
assessment = b.Assessment.ID
}
}
var attempt struct {
ID string
Questions []struct{ ID string }
}
if err := asLearner(token, "POST", "/me/enrollments/"+enrollment+"/assessments/"+assessment+"/attempts", nil, &attempt); err != nil {
return QuizResult{}, err
}
// render attempt.Questions, then send one response per question in the shape its type expects
answers := []map[string]any{{"questionId": attempt.Questions[0].ID, "response": map[string]any{"value": false}}}
var result QuizResult
err := asLearner(token, "POST", "/me/enrollments/"+enrollment+"/attempts/"+attempt.ID+"/submit", map[string]any{"answers": answers}, &result)
return result, err
}QUIZ_LESSON=$(jq -r '[.modules[].lessons[]] | map(select(.completionMode=="ASSESSMENT_PASSED"))[0].id' course.json)
ASSESSMENT=$(curl -s "$LMS_URL/api/v1/me/enrollments/$ENROLLMENT/lessons/$QUIZ_LESSON" "${H[@]}" \
| jq -r '.blocks[] | select(.type=="ASSESSMENT") | .assessment.id')
ATTEMPT=$(curl -s -X POST "$LMS_URL/api/v1/me/enrollments/$ENROLLMENT/assessments/$ASSESSMENT/attempts" "${H[@]}")
QUESTION=$(echo "$ATTEMPT" | jq -r '.questions[0].id')
curl -s -X POST "$LMS_URL/api/v1/me/enrollments/$ENROLLMENT/attempts/$(echo "$ATTEMPT" | jq -r .id)/submit" "${H[@]}" \
-d "{\"answers\":[{\"questionId\":\"$QUESTION\",\"response\":{\"value\":false}}]}"Passing completes the lesson. Finishing everything completes the course and issues the certificate (GET /me/certificates).
5. Show their courses and progress in your own screens#
Back on your server with the key. One call returns everything for a “my courses” screen or a dashboard, using your own id for the user. Add it to the same file as step 3.
export async function progress(userId) {
const courses = await lms('GET', `/learners/${userId}/courses`)
return courses.map((c) => ({ course: c.title, status: c.status, percent: c.progressPercent }))
}export async function progress(userId: string) {
const courses = await lms<{ title: string; status: string; progressPercent: number }[]>('GET', `/learners/${userId}/courses`)
return courses.map((c) => ({ course: c.title, status: c.status, percent: c.progressPercent }))
}def progress(user_id):
courses = lms("GET", f"/learners/{user_id}/courses")
return [{"course": c["title"], "status": c["status"], "percent": c["progressPercent"]} for c in courses] public static JsonNode progress(String userId) throws Exception {
return call("GET", "/learners/" + userId + "/courses", null); // title, status, progressPercent, ...
} def self.progress(user_id)
call("GET", "/learners/#{user_id}/courses").map do |c|
{ course: c["title"], status: c["status"], percent: c["progressPercent"] }
end
endfunction progress(string $userId): array
{
return array_map(
fn ($c) => ['course' => $c['title'], 'status' => $c['status'], 'percent' => $c['progressPercent']],
lms('GET', "/learners/$userId/courses"),
);
}type Progress struct {
Title string
Status string
ProgressPercent float64
}
func ProgressFor(userID string) ([]Progress, error) {
var courses []Progress
err := call("GET", "/learners/"+userID+"/courses", nil, &courses)
return courses, err
}curl "$LMS_URL/api/v1/learners/user-42/courses" -H "X-API-Key: $LMS_KEY"Each course has its title, summary, status, progressPercent, dates, and a certificateId once finished. For one course in full (every lesson with time spent, every quiz attempt with its score) use GET /learners/{id}/courses/{course}. Rather than poll, have us call you when something happens, such as enrollment.completed: Webhooks.
Next#
- The calls most apps need (create a user with a role, get their courses, remove them): Common tasks
- Everything a course player needs: Building the learner experience
- Keys, tokens and roles: Authentication
- Selling to businesses and their staff: Selling and onboarding