Moodle Web Services logo

Moodle Web Services

Community
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.

Overview

PublisherSaadRahman01
Repositoryclaude-moodle-dev
Skill namemoodle-web-services
Stars
42
Forks
7
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by SaadRahman01 on GitHub. Read the source before you install it.

Installation

Install the Moodle Web Services AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-web-services
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Moodle Web Services in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Moodle Web Services on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Moodle Web Services is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

Frequently asked questions

What does the Moodle Web Services AI skill do?

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.

Why use Moodle Web Services on TypingMind?

Because you install it once and use it with any model. Moodle Web Services is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Moodle Web Services in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-web-services. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Moodle Web Services?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Moodle Web Services?

As many as you like. As long as a model supports skills, you can use Moodle Web Services with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Moodle Web Services AI skill free?

Yes. It is published on GitHub by SaadRahman01 under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇