Construye un curso con la API¶
Esta guía crea un curso, añade un capítulo, añade una cuestionario lección, lo lee de nuevo, cambia lo de forma segura y finalmente elimina el curso — usando solo una clave API.
Usted necesita una clave con Edit (cambiar) en Cursos, Unidades (llamadas capítulos en la API) y Lecciones
(cómo obtenerla), guardada en YOSHUKO_API_KEY.
Cada llamada devuelve el objeto que creó, incluyendo su id (su ID), que usa la siguiente llamada.
1. Crea un curso¶
El slug forma parte de la dirección web del curso, así que debe ser único en tu
organización.
La respuesta es 201 Created con el nuevo curso, incluyendo su id. Tu plan tiene un límite de cursos —
la llamada se rechaza con una explicación si ya estás al límite.
2. Añade un capítulo¶
curl -sS -X POST "https://www-dev.yoshuko.com/api/v1/agent/courses/$COURSE_ID/chapters/" \
-H "Authorization: Bearer $YOSHUKO_API_KEY" \
-H "Content-Type: application/json" \
-d '{"title": "Unit 1: Materials", "position": 1}'
3. Añade una lección de cuestionario¶
El content_type de una lección dice qué tipo es (lesson, quiz, assignment …) y
content contiene el cuerpo. Para un cuestionario, eso son las preguntas:
{
"title": "Knowledge check",
"content_type": "quiz",
"position": 1,
"content": {
"title": "Knowledge check",
"passing_score": 50,
"questions": [{
"id": "q1",
"type": "multiple_choice",
"prompt_html": "<p>Which paper weight suits wet washes?</p>",
"points": 1,
"options": [
{"id": "a", "html": "300 gsm", "is_correct": true},
{"id": "b", "html": "80 gsm", "is_correct": false}
]
}]
}
}
POSTlo a /api/v1/agent/courses/{course_id}/chapters/{chapter_id}/lessons/. Se
verifica con exactamente las mismas reglas que la página donde cambias cursos en el estudio, así que un cuestionario
que no se construya correctamente se rechaza con 400 y un mensaje que nombra el campo.
4. Cambia una lección sin perder el trabajo de nadie¶
Las personas pueden estar cambiando el mismo curso en el estudio mientras tu agente trabaja. Para asegurarte
que nunca escribas sobre sus cambios sin avisar, cada cambio de lección debe enviar de vuelta el
updated_at valor que leíste la última vez:
curl -sS -X PATCH "https://www-dev.yoshuko.com/api/v1/agent/courses/$COURSE_ID/chapters/$CHAPTER_ID/lessons/$LESSON_ID/" \
-H "Authorization: Bearer $YOSHUKO_API_KEY" \
-H "Content-Type: application/json" \
-d "{\"title\": \"Quick check\", \"updated_at\": \"$UPDATED_AT\"}"
Si alguien cambió la lección después de que tú la leíste, recibes 409 con
"code": "stale_lesson" y la lección como está ahora en lesson. Haz tu
cambio nuevamente a esa versión y envíalo otra vez con su updated_at.
Todo listo, listo para ejecutar¶
Copy either program, set YOSHUKO_API_KEY, and run it. It creates a course, a chapter and a
quiz, reads the quiz back, changes it, and removes the course again so your list of courses is
left as it was.
#!/usr/bin/env bash
set -euo pipefail
BASE="https://www-dev.yoshuko.com/api/v1/agent"
AUTH="Authorization: Bearer $YOSHUKO_API_KEY"
JSON="Content-Type: application/json"
SLUG="api-demo-$(date +%s)"
COURSE_ID=$(curl -sSf -X POST "$BASE/courses/" -H "$AUTH" -H "$JSON" \
-d "{\"title\": \"API demo course\", \"slug\": \"$SLUG\"}" | jq -r .id)
echo "course $COURSE_ID"
CHAPTER_ID=$(curl -sSf -X POST "$BASE/courses/$COURSE_ID/chapters/" -H "$AUTH" -H "$JSON" \
-d '{"title": "Unit 1", "position": 1}' | jq -r .id)
echo "chapter $CHAPTER_ID"
LESSON=$(curl -sSf -X POST "$BASE/courses/$COURSE_ID/chapters/$CHAPTER_ID/lessons/" \
-H "$AUTH" -H "$JSON" -d '{
"title": "Knowledge check", "content_type": "quiz", "position": 1,
"content": {"title": "Knowledge check", "passing_score": 50, "questions": [{
"id": "q1", "type": "multiple_choice", "prompt_html": "<p>2 + 2?</p>", "points": 1,
"options": [{"id": "a", "html": "4", "is_correct": true},
{"id": "b", "html": "5", "is_correct": false}]}]}}')
LESSON_ID=$(echo "$LESSON" | jq -r .id)
UPDATED_AT=$(echo "$LESSON" | jq -r .updated_at)
echo "lesson $LESSON_ID"
curl -sSf -X PATCH "$BASE/courses/$COURSE_ID/chapters/$CHAPTER_ID/lessons/$LESSON_ID/" \
-H "$AUTH" -H "$JSON" -d "{\"title\": \"Quick check\", \"updated_at\": \"$UPDATED_AT\"}" \
| jq '{title, content_type, questions: (.content.questions | length)}'
curl -sSf -X DELETE "$BASE/courses/$COURSE_ID/" -H "$AUTH"
echo "deleted $COURSE_ID"
import os
import time
import requests
BASE = "https://www-dev.yoshuko.com/api/v1/agent"
HEADERS = {"Authorization": f"Bearer {os.environ['YOSHUKO_API_KEY']}"}
def call(method, path, **kwargs):
response = requests.request(method, BASE + path, headers=HEADERS, timeout=30, **kwargs)
response.raise_for_status()
return response.json() if response.content else None
course = call("POST", "/courses/", json={
"title": "API demo course", "slug": f"api-demo-{int(time.time())}"})
try:
chapter = call("POST", f"/courses/{course['id']}/chapters/",
json={"title": "Unit 1", "position": 1})
lessons = f"/courses/{course['id']}/chapters/{chapter['id']}/lessons/"
lesson = call("POST", lessons, json={
"title": "Knowledge check", "content_type": "quiz", "position": 1,
"content": {"title": "Knowledge check", "passing_score": 50, "questions": [{
"id": "q1", "type": "multiple_choice", "prompt_html": "<p>2 + 2?</p>",
"points": 1, "options": [{"id": "a", "html": "4", "is_correct": True},
{"id": "b", "html": "5", "is_correct": False}]}]},
})
edited = call("PATCH", f"{lessons}{lesson['id']}/",
json={"title": "Quick check", "updated_at": lesson["updated_at"]})
print(edited["title"], edited["content_type"], len(edited["content"]["questions"]))
finally:
call("DELETE", f"/courses/{course['id']}/")
print("deleted", course["id"])
Referencia¶
Todos los campos y respuestas de estos endpoints: Cursos, Capítulos, Lecciones.