Logo: Moodle Web Services

Moodle Web Services

Communautéit
SaadRahman01
moodle-web-services

Use when adding/calling Moodle web services or external functions — db/services.php, classes/external/, REST/SOAP/AJAX protocols, tokens, capabilities, parameters/returns schemas, file uploads, and rate limiting.

Iwwersiicht

EditeurSaadRahman01
Repositoryclaude-moodle-dev
Skill-Nummmoodle-web-services
Stären
42
Forks
7
Matgeliwwert Dateien
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    SaadRahman01 huet de Skill op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Moodle Web Services an TypingMind, fir e mat all LLM ze benotzen, oder setzt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vu GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier, déi hei drënner steet, an a bestätegt d'Installatioun.
    https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-web-services
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill derbäisetzen → Iwwer eng GitHub-URL. Pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an d'Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/SaadRahman01/claude-moodle-dev.git /tmp/claude-moodle-dev
mkdir -p .claude/skills
cp -r /tmp/claude-moodle-dev/skills/moodle-web-services .claude/skills/moodle-web-services
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Moodle Web Services an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Moodle Web Services automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Moodle Web Services net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Schlësselen.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Moodle Web Services

Overview

Moodle exposes plugin functions as web services via db/services.php + classes/external/<fn>.php. Same function is callable as REST, AJAX, SOAP, or XMLRPC. Authentication is token-based for external clients, session-based for AJAX. All inputs/outputs are typed via external_value / external_single_structure / external_multiple_structure.

When to Use

  • Adding a function callable from mobile app, AMD JS, or external system
  • Defining a service (bundle of functions) for an external client
  • Issuing/managing tokens
  • Returning files via web service
  • Debugging "Invalid response value" or "Missing required parameter"

Skip when: building UI-only PHP (no remote callers) — use moodle-plugin-development.

File layout

<plugin>/
  db/services.php                                # function + service definitions
  classes/external/get_items.php                 # one file per external function
  classes/external/get_items_returns.php         # (optional) split returns
  lang/en/<component>.php                        # service descriptions

db/services.php

php
<?php
defined('MOODLE_INTERNAL') || die();

$functions = [
    'local_example_get_items' => [
        'classname'    => 'local_example\external\get_items',
        'methodname'   => 'execute',                // default: 'execute'
        'description'  => 'Return items in a course',
        'type'         => 'read',                   // 'read' or 'write'
        'ajax'         => true,                     // callable from core/ajax
        'capabilities' => 'local/example:view',     // checked in addition to per-method checks
        'services'     => [MOODLE_OFFICIAL_MOBILE_SERVICE], // expose to mobile
    ],
    'local_example_mark_present' => [
        'classname'    => 'local_example\external\mark_present',
        'description'  => 'Mark a user present',
        'type'         => 'write',
        'ajax'         => true,
        'capabilities' => 'local/example:mark',
    ],
];

$services = [
    'Example REST API' => [
        'functions'         => array_keys($functions),
        'restrictedusers'   => 1,        // require explicit user assignment
        'enabled'           => 1,
        'shortname'         => 'local_example_api',
        'downloadfiles'     => 1,
        'uploadfiles'       => 0,
    ],
];

After editing: bump version.php, run php admin/cli/upgrade.php.

External function class

php
<?php
namespace local_example\external;
defined('MOODLE_INTERNAL') || die();

use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_value;
use core_external\external_single_structure;
use core_external\external_multiple_structure;

class get_items extends external_api {

    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'courseid' => new external_value(PARAM_INT, 'Course ID'),
            'limit'    => new external_value(PARAM_INT, 'Max items', VALUE_DEFAULT, 50),
        ]);
    }

    public static function execute(int $courseid, int $limit = 50): array {
        global $DB, $USER;

        // 1. Validate params (re-runs schema, normalizes types)
        $params = self::validate_parameters(self::execute_parameters(), [
            'courseid' => $courseid,
            'limit'    => $limit,
        ]);

        // 2. Validate context + capability
        $context = \context_course::instance($params['courseid']);
        self::validate_context($context);
        require_capability('local/example:view', $context);

        // 3. Business logic
        $rows = $DB->get_records('local_example_items',
            ['courseid' => $params['courseid']], 'timecreated DESC', '*', 0, $params['limit']);

        return array_values(array_map(fn($r) => [
            'id'   => (int)$r->id,
            'name' => format_string($r->name, true, ['context' => $context]),
            'time' => (int)$r->timecreated,
        ], $rows));
    }

    public static function execute_returns(): external_multiple_structure {
        return new external_multiple_structure(
            new external_single_structure([
                'id'   => new external_value(PARAM_INT, 'ID'),
                'name' => new external_value(PARAM_TEXT, 'Name'),
                'time' => new external_value(PARAM_INT, 'Created timestamp'),
            ])
        );
    }
}

Required ordering inside execute():

  1. validate_parameters()
  2. validate_context()
  3. require_capability()
  4. business logic
  5. format output (format_string, format_text with context)

Skipping any of (1)-(3) is a security bug.

Moodle version notes

MoodleNamespace
4.2+core_external\external_api (etc.)
≤ 4.1bare external_api (no namespace)

For 4.2+ compatibility wrappers, see lib/classes/external/.

Parameter types (PARAM_*)

ConstantUse
PARAM_INTIntegers
PARAM_FLOATDecimals
PARAM_BOOLtrue/false
PARAM_TEXTPlain text (strips tags)
PARAM_RAWUntrusted text — use only if you re-format on output
PARAM_NOTAGSStrips tags, keeps entities
PARAM_CLEANHTMLSanitized HTML
PARAM_ALPHANUMa-zA-Z0-9
PARAM_ALPHAa-zA-Z
PARAM_USERNAMEValidates Moodle username
PARAM_EMAILValidates email
PARAM_URLValidates URL
PARAM_FILEFilename (no path)
PARAM_PATHPath (no ..)
PARAM_COMPONENTfrankenstyle (local_example)
PARAM_CAPABILITYlocal/example:view
PARAM_PLUGIN<name> part
PARAM_AREAFile area names
PARAM_BASE64Base64

VALUE_REQUIRED (default), VALUE_OPTIONAL (omit from response if null), VALUE_DEFAULT (with default).

Calling from REST

bash
TOKEN=abcdef0123456789
SITE=https://moodle.example.com

curl -X POST "$SITE/webservice/rest/server.php" \
  -d "wstoken=$TOKEN" \
  -d "moodlewsrestformat=json" \
  -d "wsfunction=local_example_get_items" \
  -d "courseid=5" \
  -d "limit=10"

Response on error:

json
{"exception":"invalid_parameter_exception","errorcode":"invalidparameter","message":"..."}

Calling from AJAX (browser)

javascript
import Ajax from 'core/ajax';

const [items] = await Ajax.call([{
    methodname: 'local_example_get_items',
    args: {courseid: 5, limit: 10},
}]);

Requires 'ajax' => true in db/services.php. Session cookie auths; no token needed.

Token issuance

bash
# Site admin > Server > Web services > Manage tokens
# or programmatically:
php
$service = $DB->get_record('external_services', ['shortname' => 'local_example_api']);
$token = \core_external\util::generate_token(
    EXTERNAL_TOKEN_PERMANENT,
    $service,
    $userid,
    \context_system::instance()
);

File uploads via web service

  1. Upload to draft area: POST /webservice/upload.php?token=$T&filearea=draft&itemid=0
  2. Returns itemid
  3. Pass that itemid to your function via a PARAM_INT param
  4. In execute(), move from draft to plugin area:
php
file_save_draft_area_files($params['draftitemid'], $context->id,
    'local_example', 'attachments', $itemid,
    ['subdirs' => 0, 'maxfiles' => 5]);

Service must have uploadfiles => 1.

File downloads

Set downloadfiles => 1 on service, serve via pluginfile.php. Token-authed clients append ?token=$T to pluginfile URLs.

Rate limiting

No built-in per-token rate limit. Options:

  • \core\session\manager::is_loggedinas() checks
  • Custom middleware via lib/setuplib.php hook
  • Reverse-proxy rate limit (nginx limit_req)

Common Mistakes

MistakeFix
Skipping validate_parameters()Always call first — ensures types match schema
Skipping validate_context()Required for capability + permission scoping
Returning unformatted user textRun through format_string() / format_text() with context
Schema mismatch in returnsWrap response with clean_returnvalue in tests
Wrong namespace pre-4.2Use external_api bare; for 4.2+ use core_external\external_api
'ajax' => true missing for browser callsCalls fail with accessexception
Not bumping version.php after db/services.php changeService won't register — bump + upgrade
Token user lacks required capabilityrequire_capability fails — assign user to service or grant cap
restrictedusers => 1 but no users assignedSite admin > Server > Web services > Authorised users
MOODLE_OFFICIAL_MOBILE_SERVICE exposes more than intendedAudit — only add functions safe for mobile app

Testing

php
// tests/external/get_items_test.php
$this->setUser($user);
$result = get_items::execute($course->id, 10);
$result = external_api::clean_returnvalue(get_items::execute_returns(), $result);
$this->assertCount(2, $result);

clean_returnvalue is mandatory — catches return schema bugs.

References

Heefeg gestallte Froen

Wat mécht de KI-Skill Moodle Web Services?

Use when adding/calling Moodle web services or external functions — db/services.php, classes/external/, REST/SOAP/AJAX protocols, tokens, capabilities, parameters/returns schemas, file uploads, and rate limiting.

Firwat Moodle Web Services op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Moodle Web Services besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt, amplaz en Abonnement pro Benotzerplaz ze bezuelen. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Moodle Web Services an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-web-services an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Moodle Web Services benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Moodle Web Services benotzen?

Esou vill wéi Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Moodle Web Services domat benotzen – zum Beispill mat GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Moodle Web Services gratis?

Jo. SaadRahman01 huet de Skill ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbare Pak vun Instruktiounen, deen engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt e maache soll a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a kee Lafzäitëmfeld a funktionéiere mat all Modell.

Alleguer weisen

Elo Ären eegene KI-Aarbechtsberäich ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇