💼 Moodle External API Development
Moodle(ムードル)という学習管理システムに
📺 まず動画で見る(YouTube)
▶ 【自動化】AIガチ勢の最新活用術6選がこれ1本で丸分かり!【ClaudeCode・AIエージェント・AI経営・Skills・MCP】 ↗
※ jpskill.com 編集部が参考用に選んだ動画です。動画の内容と Skill の挙動は厳密には一致しないことがあります。
📜 元の英語説明(参考)
Create custom external web service APIs for Moodle LMS. Use when implementing web services for course management, user tracking, quiz operations, or custom plugin functionality. Covers parameter validation, database operations, error handling, service registration, and Moodle coding standards.
🇯🇵 日本人クリエイター向け解説
Moodle(ムードル)という学習管理システムに
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o moodle-external-api-development.zip https://jpskill.com/download/425.zip && unzip -o moodle-external-api-development.zip && rm moodle-external-api-development.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/425.zip -OutFile "$d\moodle-external-api-development.zip"; Expand-Archive "$d\moodle-external-api-development.zip" -DestinationPath $d -Force; ri "$d\moodle-external-api-development.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
moodle-external-api-development.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
moodle-external-api-developmentフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-17
- 取得日時
- 2026-05-17
- 同梱ファイル
- 1
💬 こう話しかけるだけ — サンプルプロンプト
- › moodle-external-api-developmen を使って、最小構成のサンプルコードを示して
- › moodle-external-api-developmen の主な使い方と注意点を教えて
- › moodle-external-api-developmen を既存プロジェクトに組み込む方法を教えて
これをClaude Code に貼るだけで、このSkillが自動発動します。
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
Moodle 外部 API 開発
このスキルでは、Moodle の外部 API フレームワークとコーディング標準に従って、Moodle LMS 用のカスタム外部 Web サービス API を作成する方法を説明します。
このスキルを使用するタイミング
- Moodle プラグイン用のカスタム Web サービスを作成する場合
- コース管理用の REST/AJAX エンドポイントを実装する場合
- クイズ操作、ユーザー追跡、またはレポート作成用の API を構築する場合
- Moodle の機能を外部アプリケーションに公開する場合
- Moodle を使用してモバイルアプリのバックエンドを開発する場合
コアアーキテクチャパターン
Moodle の外部 API は、厳密な 3 つのメソッドパターンに従います。
execute_parameters()- 入力パラメータ構造を定義しますexecute()- ビジネスロジックを含みますexecute_returns()- 戻り値構造を定義します
ステップバイステップの実装
ステップ 1: 外部 API クラスファイルを作成する
場所: /local/yourplugin/classes/external/your_api_name.php
<?php
namespace local_yourplugin\external;
defined('MOODLE_INTERNAL') || die();
require_once("$CFG->libdir/externallib.php");
use external_api;
use external_function_parameters;
use external_single_structure;
use external_value;
class your_api_name extends external_api {
// Three required methods will go here
}
重要なポイント:
- クラスは
external_apiを継承する必要があります - 名前空間は
local_pluginname\externalまたはmod_modname\externalに従います - セキュリティチェック
defined('MOODLE_INTERNAL') || die();を含めます - 基本クラスのために externallib.php を require します
ステップ 2: 入力パラメータを定義する
public static function execute_parameters() {
return new external_function_parameters([
'userid' => new external_value(PARAM_INT, 'User ID', VALUE_REQUIRED),
'courseid' => new external_value(PARAM_INT, 'Course ID', VALUE_REQUIRED),
'options' => new external_single_structure([
'includedetails' => new external_value(PARAM_BOOL, 'Include details', VALUE_DEFAULT, false),
'limit' => new external_value(PARAM_INT, 'Result limit', VALUE_DEFAULT, 10)
], 'Options', VALUE_OPTIONAL)
]);
}
一般的なパラメータタイプ:
PARAM_INT- 整数PARAM_TEXT- プレーンテキスト (HTML は除去されます)PARAM_RAW- 生のテキスト (クリーニングなし)PARAM_BOOL- 真偽値PARAM_FLOAT- 浮動小数点数PARAM_ALPHANUMEXT- 拡張文字を含む英数字
構造:
external_value- 単一の値external_single_structure- 名前付きフィールドを持つオブジェクトexternal_multiple_structure- アイテムの配列
値フラグ:
VALUE_REQUIRED- パラメータは必須ですVALUE_OPTIONAL- パラメータはオプションですVALUE_DEFAULT, defaultvalue- デフォルト値を持つオプション
ステップ 3: ビジネスロジックを実装する
public static function execute($userid, $courseid, $options = []) {
global $DB, $USER;
// 1. Validate parameters
$params = self::validate_parameters(self::execute_parameters(), [
'userid' => $userid,
'courseid' => $courseid,
'options' => $options
]);
// 2. Check permissions/capabilities
$context = \context_course::instance($params['courseid']);
self::validate_context($context);
require_capability('moodle/course:view', $context);
// 3. Verify user access
if ($params['userid'] != $USER->id) {
require_capability('moodle/course:viewhiddenactivities', $context);
}
// 4. Database operations
$sql = "SELECT id, name, timecreated
FROM {your_table}
WHERE userid = :userid
AND courseid = :courseid
LIMIT :limit";
$records = $DB->get_records_sql($sql, [
'userid' => $params['userid'],
'courseid' => $params['courseid'],
'limit' => $params['options']['limit']
]);
// 5. Process and return data
$results = [];
foreach ($records as $record) {
$results[] = [
'id' => $record->id,
'name' => $record->name,
'timestamp' => $record->timecreated
];
}
return [
'items' => $results,
'count' => count($results)
];
}
重要なステップ:
validate_parameters()を使用して常にパラメータを検証しますvalidate_context()を使用してコンテキストをチェックしますrequire_capability()を使用して権限を検証します- SQL インジェクションを防ぐためにパラメータ化されたクエリを使用します
- 戻り値の定義に一致する構造化データを返します
ステップ 4: 戻り値の構造を定義する
public static function execute_returns() {
return new external_single_structure([
'items' => new external_multiple_structure(
new external_single_structure([
'id' => new external_value(PARAM_INT, 'Item ID'),
'name' => new external_value(PARAM_TEXT, 'Item name'),
'timestamp' => new external_value(PARAM_INT, 'Creation time')
])
),
'count' => new external_value(PARAM_INT, 'Total items')
]);
}
戻り値の構造ルール:
execute()が返すものと完全に一致する必要があります- 適切なパラメータタイプを使用します
- 各フィールドを説明付きで文書化します
- ネストされた構造も許可されます
ステップ 5: サービスを登録する
場所: /local/yourplugin/db/services.php
<?php
defined('MOODLE_INTERNAL') || die();
$functions = [
'local_yourplugin_your_api_name' => [
'classname' => 'local_yourplugin\external\your_api_name',
'methodname' => 'execute',
'classpath' => 'local/yourplugin/classes/external/your_api_name.php',
'description' => 'Brief description of what this API does',
'type' => 'read', // or 'write'
'ajax' => true,
'capabilities'=> 'moodle/course:view', // comma-separated if multiple
'services' => [MOODLE_OFFICIAL_MOBILE_SERVICE] // Optional
],
];
$services = [
'Your Plugin Web Service' => [
'functions' => [
'local_yourplugin_your_api_name'
],
'restrictedusers' => 0,
'enabled' => 1
]
];
サービス R
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Moodle External API Development
This skill guides you through creating custom external web service APIs for Moodle LMS, following Moodle's external API framework and coding standards.
When to Use This Skill
- Creating custom web services for Moodle plugins
- Implementing REST/AJAX endpoints for course management
- Building APIs for quiz operations, user tracking, or reporting
- Exposing Moodle functionality to external applications
- Developing mobile app backends using Moodle
Core Architecture Pattern
Moodle external APIs follow a strict three-method pattern:
execute_parameters()- Defines input parameter structureexecute()- Contains business logicexecute_returns()- Defines return structure
Step-by-Step Implementation
Step 1: Create the External API Class File
Location: /local/yourplugin/classes/external/your_api_name.php
<?php
namespace local_yourplugin\external;
defined('MOODLE_INTERNAL') || die();
require_once("$CFG->libdir/externallib.php");
use external_api;
use external_function_parameters;
use external_single_structure;
use external_value;
class your_api_name extends external_api {
// Three required methods will go here
}
Key Points:
- Class must extend
external_api - Namespace follows:
local_pluginname\externalormod_modname\external - Include the security check:
defined('MOODLE_INTERNAL') || die(); - Require externallib.php for base classes
Step 2: Define Input Parameters
public static function execute_parameters() {
return new external_function_parameters([
'userid' => new external_value(PARAM_INT, 'User ID', VALUE_REQUIRED),
'courseid' => new external_value(PARAM_INT, 'Course ID', VALUE_REQUIRED),
'options' => new external_single_structure([
'includedetails' => new external_value(PARAM_BOOL, 'Include details', VALUE_DEFAULT, false),
'limit' => new external_value(PARAM_INT, 'Result limit', VALUE_DEFAULT, 10)
], 'Options', VALUE_OPTIONAL)
]);
}
Common Parameter Types:
PARAM_INT- IntegersPARAM_TEXT- Plain text (HTML stripped)PARAM_RAW- Raw text (no cleaning)PARAM_BOOL- Boolean valuesPARAM_FLOAT- Floating point numbersPARAM_ALPHANUMEXT- Alphanumeric with extended chars
Structures:
external_value- Single valueexternal_single_structure- Object with named fieldsexternal_multiple_structure- Array of items
Value Flags:
VALUE_REQUIRED- Parameter must be providedVALUE_OPTIONAL- Parameter is optionalVALUE_DEFAULT, defaultvalue- Optional with default
Step 3: Implement Business Logic
public static function execute($userid, $courseid, $options = []) {
global $DB, $USER;
// 1. Validate parameters
$params = self::validate_parameters(self::execute_parameters(), [
'userid' => $userid,
'courseid' => $courseid,
'options' => $options
]);
// 2. Check permissions/capabilities
$context = \context_course::instance($params['courseid']);
self::validate_context($context);
require_capability('moodle/course:view', $context);
// 3. Verify user access
if ($params['userid'] != $USER->id) {
require_capability('moodle/course:viewhiddenactivities', $context);
}
// 4. Database operations
$sql = "SELECT id, name, timecreated
FROM {your_table}
WHERE userid = :userid
AND courseid = :courseid
LIMIT :limit";
$records = $DB->get_records_sql($sql, [
'userid' => $params['userid'],
'courseid' => $params['courseid'],
'limit' => $params['options']['limit']
]);
// 5. Process and return data
$results = [];
foreach ($records as $record) {
$results[] = [
'id' => $record->id,
'name' => $record->name,
'timestamp' => $record->timecreated
];
}
return [
'items' => $results,
'count' => count($results)
];
}
Critical Steps:
- Always validate parameters using
validate_parameters() - Check context using
validate_context() - Verify capabilities using
require_capability() - Use parameterized queries to prevent SQL injection
- Return structured data matching return definition
Step 4: Define Return Structure
public static function execute_returns() {
return new external_single_structure([
'items' => new external_multiple_structure(
new external_single_structure([
'id' => new external_value(PARAM_INT, 'Item ID'),
'name' => new external_value(PARAM_TEXT, 'Item name'),
'timestamp' => new external_value(PARAM_INT, 'Creation time')
])
),
'count' => new external_value(PARAM_INT, 'Total items')
]);
}
Return Structure Rules:
- Must match exactly what
execute()returns - Use appropriate parameter types
- Document each field with description
- Nested structures allowed
Step 5: Register the Service
Location: /local/yourplugin/db/services.php
<?php
defined('MOODLE_INTERNAL') || die();
$functions = [
'local_yourplugin_your_api_name' => [
'classname' => 'local_yourplugin\external\your_api_name',
'methodname' => 'execute',
'classpath' => 'local/yourplugin/classes/external/your_api_name.php',
'description' => 'Brief description of what this API does',
'type' => 'read', // or 'write'
'ajax' => true,
'capabilities'=> 'moodle/course:view', // comma-separated if multiple
'services' => [MOODLE_OFFICIAL_MOBILE_SERVICE] // Optional
],
];
$services = [
'Your Plugin Web Service' => [
'functions' => [
'local_yourplugin_your_api_name'
],
'restrictedusers' => 0,
'enabled' => 1
]
];
Service Registration Keys:
classname- Full namespaced class namemethodname- Always 'execute'type- 'read' (SELECT) or 'write' (INSERT/UPDATE/DELETE)ajax- Set true for AJAX/REST accesscapabilities- Required Moodle capabilitiesservices- Optional service bundles
Step 6: Implement Error Handling & Logging
private static function log_debug($message) {
global $CFG;
$logdir = $CFG->dataroot . '/local_yourplugin';
if (!file_exists($logdir)) {
mkdir($logdir, 0777, true);
}
$debuglog = $logdir . '/api_debug.log';
$timestamp = date('Y-m-d H:i:s');
file_put_contents($debuglog, "[$timestamp] $message\n", FILE_APPEND | LOCK_EX);
}
public static function execute($userid, $courseid) {
global $DB;
try {
self::log_debug("API called: userid=$userid, courseid=$courseid");
// Validate parameters
$params = self::validate_parameters(self::execute_parameters(), [
'userid' => $userid,
'courseid' => $courseid
]);
// Your logic here
self::log_debug("API completed successfully");
return $result;
} catch (\invalid_parameter_exception $e) {
self::log_debug("Parameter validation failed: " . $e->getMessage());
throw $e;
} catch (\moodle_exception $e) {
self::log_debug("Moodle exception: " . $e->getMessage());
throw $e;
} catch (\Exception $e) {
// Log detailed error info
$lastsql = method_exists($DB, 'get_last_sql') ? $DB->get_last_sql() : '[N/A]';
self::log_debug("Fatal error: " . $e->getMessage());
self::log_debug("Last SQL: " . $lastsql);
self::log_debug("Stack trace: " . $e->getTraceAsString());
throw $e;
}
}
Error Handling Best Practices:
- Wrap logic in try-catch blocks
- Log errors with timestamps and context
- Capture SQL queries on database errors
- Preserve stack traces for debugging
- Re-throw exceptions after logging
Advanced Patterns
Complex Database Operations
// Transaction example
$transaction = $DB->start_delegated_transaction();
try {
// Insert record
$recordid = $DB->insert_record('your_table', $dataobject);
// Update related records
$DB->set_field('another_table', 'status', 1, ['recordid' => $recordid]);
// Commit transaction
$transaction->allow_commit();
} catch (\Exception $e) {
$transaction->rollback($e);
throw $e;
}
Working with Course Modules
// Create course module
$moduleid = $DB->get_field('modules', 'id', ['name' => 'quiz'], MUST_EXIST);
$cm = new \stdClass();
$cm->course = $courseid;
$cm->module = $moduleid;
$cm->instance = 0; // Will be updated after activity creation
$cm->visible = 1;
$cm->groupmode = 0;
$cmid = add_course_module($cm);
// Create activity instance (e.g., quiz)
$quiz = new \stdClass();
$quiz->course = $courseid;
$quiz->name = 'My Quiz';
$quiz->coursemodule = $cmid;
// ... other quiz fields ...
$quizid = quiz_add_instance($quiz, null);
// Update course module with instance ID
$DB->set_field('course_modules', 'instance', $quizid, ['id' => $cmid]);
course_add_cm_to_section($courseid, $cmid, 0);
Access Restrictions (Groups/Availability)
// Restrict activity to specific user via group
$groupname = 'activity_' . $activityid . '_user_' . $userid;
// Create or get group
if (!$groupid = $DB->get_field('groups', 'id', ['courseid' => $courseid, 'name' => $groupname])) {
$groupdata = (object)[
'courseid' => $courseid,
'name' => $groupname,
'timecreated' => time(),
'timemodified' => time()
];
$groupid = $DB->insert_record('groups', $groupdata);
}
// Add user to group
if (!$DB->record_exists('groups_members', ['groupid' => $groupid, 'userid' => $userid])) {
$DB->insert_record('groups_members', (object)[
'groupid' => $groupid,
'userid' => $userid,
'timeadded' => time()
]);
}
// Set availability condition
$restriction = [
'op' => '&',
'show' => false,
'c' => [
[
'type' => 'group',
'id' => $groupid
]
],
'showc' => [false]
];
$DB->set_field('course_modules', 'availability', json_encode($restriction), ['id' => $cmid]);
Random Question Selection with Tags
private static function get_random_questions($categoryid, $tagname, $limit) {
global $DB;
$sql = "SELECT q.id
FROM {question} q
INNER JOIN {question_versions} qv ON qv.questionid = q.id
INNER JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
INNER JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
JOIN {tag_instance} ti ON ti.itemid = q.id
JOIN {tag} t ON t.id = ti.tagid
WHERE LOWER(t.name) = :tagname
AND qc.id = :categoryid
AND ti.itemtype = 'question'
AND q.qtype = 'multichoice'";
$qids = $DB->get_fieldset_sql($sql, [
'categoryid' => $categoryid,
'tagname' => strtolower($tagname)
]);
shuffle($qids);
return array_slice($qids, 0, $limit);
}
Testing Your API
1. Via Moodle Web Services Test Client
- Enable web services: Site administration > Advanced features
- Enable REST protocol: Site administration > Plugins > Web services > Manage protocols
- Create service: Site administration > Server > Web services > External services
- Test function: Site administration > Development > Web service test client
2. Via curl
# Get token first
curl -X POST "https://yourmoodle.com/login/token.php" \
-d "username=admin" \
-d "password=yourpassword" \
-d "service=moodle_mobile_app"
# Call your API
curl -X POST "https://yourmoodle.com/webservice/rest/server.php" \
-d "wstoken=YOUR_TOKEN" \
-d "wsfunction=local_yourplugin_your_api_name" \
-d "moodlewsrestformat=json" \
-d "userid=2" \
-d "courseid=3"
3. Via JavaScript (AJAX)
require(['core/ajax'], function(ajax) {
var promises = ajax.call([{
methodname: 'local_yourplugin_your_api_name',
args: {
userid: 2,
courseid: 3
}
}]);
promises[0].done(function(response) {
console.log('Success:', response);
}).fail(function(error) {
console.error('Error:', error);
});
});
Common Pitfalls & Solutions
1. "Function not found" Error
Solution:
- Purge caches: Site administration > Development > Purge all caches
- Verify function name in services.php matches exactly
- Check namespace and class name are correct
2. "Invalid parameter value detected"
Solution:
- Ensure parameter types match between definition and usage
- Check required vs optional parameters
- Validate nested structure definitions
3. SQL Injection Vulnerabilities
Solution:
- Always use placeholder parameters (
:paramname) - Never concatenate user input into SQL strings
- Use Moodle's database methods:
get_record(),get_records(), etc.
4. Permission Denied Errors
Solution:
- Call
self::validate_context($context)early in execute() - Check required capabilities match user's permissions
- Verify user has role assignments in the context
5. Transaction Deadlocks
Solution:
- Keep transactions short
- Always commit or rollback in finally blocks
- Avoid nested transactions
Debugging Checklist
- [ ] Check Moodle debug mode: Site administration > Development > Debugging
- [ ] Review web services logs: Site administration > Reports > Logs
- [ ] Check custom log files in
$CFG->dataroot/local_yourplugin/ - [ ] Verify database queries using
$DB->set_debug(true) - [ ] Test with admin user to rule out permission issues
- [ ] Clear browser cache and Moodle caches
- [ ] Check PHP error logs on server
Plugin Structure Checklist
local/yourplugin/
├── version.php # Plugin version and metadata
├── db/
│ ├── services.php # External service definitions
│ └── access.php # Capability definitions (optional)
├── classes/
│ └── external/
│ ├── your_api_name.php # External API implementation
│ └── another_api.php # Additional APIs
├── lang/
│ └── en/
│ └── local_yourplugin.php # Language strings
└── tests/
└── external_test.php # Unit tests (optional but recommended)
Examples from Real Implementation
Simple Read API (Get Quiz Attempts)
<?php
namespace local_userlog\external;
defined('MOODLE_INTERNAL') || die();
require_once("$CFG->libdir/externallib.php");
use external_api;
use external_function_parameters;
use external_single_structure;
use external_value;
class get_quiz_attempts extends external_api {
public static function execute_parameters() {
return new external_function_parameters([
'userid' => new external_value(PARAM_INT, 'User ID'),
'courseid' => new external_value(PARAM_INT, 'Course ID')
]);
}
public static function execute($userid, $courseid) {
global $DB;
self::validate_parameters(self::execute_parameters(), [
'userid' => $userid,
'courseid' => $courseid
]);
$sql = "SELECT COUNT(*) AS quiz_attempts
FROM {quiz_attempts} qa
JOIN {quiz} q ON qa.quiz = q.id
WHERE qa.userid = :userid AND q.course = :courseid";
$attempts = $DB->get_field_sql($sql, [
'userid' => $userid,
'courseid' => $courseid
]);
return ['quiz_attempts' => (int)$attempts];
}
public static function execute_returns() {
return new external_single_structure([
'quiz_attempts' => new external_value(PARAM_INT, 'Total number of quiz attempts')
]);
}
}
Complex Write API (Create Quiz from Categories)
See attached create_quiz_from_categories.php for a comprehensive example including:
- Multiple database insertions
- Course module creation
- Quiz instance configuration
- Random question selection with tags
- Group-based access restrictions
- Extensive error logging
- Transaction management
Quick Reference: Common Moodle Tables
| Table | Purpose |
|---|---|
{user} |
User accounts |
{course} |
Courses |
{course_modules} |
Activity instances in courses |
{modules} |
Available activity types (quiz, forum, etc.) |
{quiz} |
Quiz configurations |
{quiz_attempts} |
Quiz attempt records |
{question} |
Question bank |
{question_categories} |
Question categories |
{grade_items} |
Gradebook items |
{grade_grades} |
Student grades |
{groups} |
Course groups |
{groups_members} |
Group memberships |
{logstore_standard_log} |
Activity logs |
Additional Resources
- Moodle External API Documentation
- Moodle Coding Style
- Moodle Database API
- Web Services API Documentation
Guidelines
- Always validate input parameters using
validate_parameters() - Check user context and capabilities before operations
- Use parameterized SQL queries (never string concatenation)
- Implement comprehensive error handling and logging
- Follow Moodle naming conventions (lowercase, underscores)
- Document all parameters and return values clearly
- Test with different user roles and permissions
- Consider transaction safety for write operations
- Purge caches after service registration changes
- Keep API methods focused and single-purpose