Token导航 LogoToken导航

Agent Skill · 开发

moodle-external-api-development(moodle external API 开发)

用于辅助 API 设计、接口文档、请求响应结构和服务集成说明。它适合让 Agent 梳理 endpoint、生成 OpenAPI 草稿、检查字段命名、整理错误码或辅助前后端联调。使用时需要确认真实业务语义、鉴权方式、分页和错误处理规则;涉及生成接口文档时,应避免凭空补字段,最好从现有代码、schema 或接口样例中提取事实。

moodle-external-api-development 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为调用外部服务;许可证为 MIT,第三方扫描有未通过项,按安装量在开发类的 21,746 个 Skill 里排第 6,892。

总安装 4,248周安装 177GitHub Stars 26,412下载 1,416核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:moodle-external-api-development(moodle external API 开发)
来源仓库:https://github.com/davila7/claude-code-templates
仓库路径:skills/moodle-external-api-development
安装命令:
npx skills add https://github.com/davila7/claude-code-templates --skill moodle-external-api-development
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/davila7/claude-code-templates --skill moodle-external-api-development

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

Moodle LMS 外部 Web 服务开发规范,遵循 RESTful 接口标准。定义 execute_parameters() 等方法签名与参数验证逻辑。支持课程管理、测验操作与用户跟踪等功能扩展。需启用 Moodle 的 external services 插件配置。

moodle-external-api-development 属于开发类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/moodle-external-api-development

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/davila7/claude-code-templates --skill moodle-e…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要调用外部服务,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

moodle-external-api-development 怎么安装?

在终端执行 npx skills add https://github.com/davila7/claude-code-templates --skill moodle-external-ap…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

moodle-external-api-development 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

moodle-external-api-development 需要什么权限?

权限级别是调用外部服务。该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

moodle-external-api-development 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

moodle-external-api-development 用的人多吗?

公开数据是累计安装 4,248 次,近一周安装 177 次,下载 1,416 次,GitHub 26,412 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

moodle-external-api-development 安全吗?

第三方扫描有未通过项,风险较高。除非你确认过源码,否则不建议直接安装到常用环境。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。
  • 来源仓库有 26,412 星,维护活跃度相对可查。

先想清楚的地方

  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
moodle-external-api-development

moodle external API 开发 · 本页

4,24826,412调用外部服务MIT未通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

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:

  1. execute_parameters() - Defines input parameter structure
  2. execute() - Contains business logic
  3. execute_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\external or mod_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 - Integers
  • PARAM_TEXT - Plain text (HTML stripped)
  • PARAM_RAW - Raw text (no cleaning)
  • PARAM_BOOL - Boolean values
  • PARAM_FLOAT - Floating point numbers
  • PARAM_ALPHANUMEXT - Alphanumeric with extended chars

Structures:

  • external_value - Single value
  • external_single_structure - Object with named fields
  • external_multiple_structure - Array of items

Value Flags:

  • VALUE_REQUIRED - Parameter must be provided
  • VALUE_OPTIONAL - Parameter is optional
  • VALUE_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:

  1. Always validate parameters using validate_parameters()
  2. Check context using validate_context()
  3. Verify capabilities using require_capability()
  4. Use parameterized queries to prevent SQL injection
  5. 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 name
  • methodname - Always 'execute'
  • type - 'read' (SELECT) or 'write' (INSERT/UPDATE/DELETE)
  • ajax - Set true for AJAX/REST access
  • capabilities - Required Moodle capabilities
  • services - 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

  1. Enable web services: Site administration > Advanced features
  2. Enable REST protocol: Site administration > Plugins > Web services > Manage protocols
  3. Create service: Site administration > Server > Web services > External services
  4. 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

TablePurpose
{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

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

平台分布

Claude Code

31.74%
按下载量换算449

OpenCode

24.76%
按下载量换算351

Cursor

16.08%
按下载量换算228

Gemini CLI

12.27%
按下载量换算174

Antigravity

8.2%
按下载量换算116

windsurf

3.81%
按下载量换算54

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

未通过

权限和风险

调用外部服务

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。

继续浏览同类 Skills