When a custom Moodle web service function is the right integration method
A custom web service function is the right answer when an HR, student information or reporting system needs to read or write Moodle data and no function in core covers that exact operation. Moodle's External API lets an external system call PHP functions over web service protocols using a token issued for a dedicated service user. Before building anything, check whether a core function already returns the data or performs the action, because core functions are maintained by Moodle HQ and upgraded with the platform. Also check whether the need is really a new Moodle feature or a configuration change, such as enrolment or authentication plugins that keep users and memberships in sync without custom code.
A direct database read is the wrong shortcut for most integrations. It bypasses capability checks, skips the business logic in Moodle's own APIs, and ties your integration to table layouts that change between releases. A custom function, by contrast, runs inside Moodle, can apply the same capability checks a user would face, and returns data in a documented shape. The trade-off is that the function becomes a maintained interface with its own security surface: it is reachable by any token holder whose service includes it, it must be tested after every Moodle upgrade, and it must be documented for the people who consume it. Plan for an owner, a test suite and a deprecation path from the start.
Confirm the exact External API behavior for your target version before you commit to this method. Check how the web service is enabled, how tokens are issued and scoped, which protocols your version exposes, and how the external function description must be declared. Ask your team to verify these details against the Moodle developer documentation for that release at Moodle developer docs and in a test site, since the platform's release cycle means details can shift between versions. If the integration needs identity federation rather than data access, a separate authentication decision applies.
Which integration pattern fits which need
This table compares four ways to expose data or operations to an external system: core web service functions, a custom function in a local plugin, a custom function in a dedicated service, and direct database access or a scheduled export. Read each row against the integration you are planning, then check who carries the upgrade and support burden before choosing.
| Pattern | When it fits | Who maintains it across upgrades | Main risk |
|---|---|---|---|
| Core web service functions | The operation already exists in Moodle's External API and the consumer only needs standard reads or writes | Moodle HQ maintains the function; your team tracks deprecations in each release | Missing data or operations that core does not expose, forcing workarounds |
| Custom function in a local plugin | You need a small number of site-specific operations on existing Moodle data, owned by one team | Your team or partner maintains the plugin code and retests it on every Moodle upgrade | Capability checks or parameter validation left incomplete, exposing data to the wrong users |
| Custom function in a dedicated service | Several consumers need a stable, scoped set of functions with their own token and permissions | Your team owns the service definition, the function list and the consumer documentation | Functions added to a shared service grow beyond their intended consumers and become hard to review |
| Direct database integration or scheduled export | The consumer is a reporting or archive job that reads data in batches and never writes back | Your team owns the queries, which break when Moodle changes its schema between releases | Bypasses Moodle capability checks and business logic, so access and data rules must be rebuilt outside Moodle |
How to build and expose a custom function step by step
This sequence takes a custom operation from a scoped requirement to a tested external function that a named service exposes to a token holder. Each step closes with a check so the integration team can confirm the function behaves correctly before any consumer depends on it.
Scope the operations and data
The client's integration owner and a Moodle developer agree which operations the external system needs, such as reading course completion or creating an enrolment, and which records and fields each call returns or changes. Record the capability each operation must respect and the user role that will call it. The step is done when the list of functions, inputs, outputs and required capabilities is written down and signed off by the people who own the data.
Create a local plugin to hold the code
A developer creates a local plugin under the local directory of the Moodle codebase, with a version file and a component name that follows Moodle's naming conventions. Keeping custom code in a local plugin means core files stay untouched, so future Moodle upgrades do not overwrite the work. Confirm the plugin appears under the site's plugin list in site administration and that the site upgrade runs without errors after installation.
Write the function definition and implementation
The developer adds a db/services.php file in the plugin that declares each function name, the class that implements it, the capability it requires, and its access type. The implementation lives in an external class that extends Moodle's external API base class, with a parameters definition, an execute method and a returns definition. Confirm by running the site's cache purge and checking that the new function is listed in the external functions registry, with no PHP errors in the logs.
Add capability checks and parameter validation
Inside execute, the developer validates parameters through the external API's parameter types, then resolves the context for the target object and calls the capability check for the calling user before reading or writing data. Any input that identifies a course, user or module is checked for existence and for the caller's access to that object. Confirm with unit or behat-style tests that invalid input returns a clear error and that a user without the capability receives an access exception rather than data.
Register the function in a service
An administrator creates or selects an external service in site administration, then adds the new function to it. Only functions the integration needs should be added to a dedicated service, so the token scope stays narrow. Confirm that the service's function list shows the new function and that no unrelated functions were added by accident.
Enable the web service and protocol
The site administrator enables web services in advanced features and turns on the REST protocol, if the consumer uses it, in the web services settings. The administrator also confirms that the service is enabled and that the authorised user for the service has only the roles needed for the integration. The step is done when a request to the service endpoint returns a structured response rather than a disabled-service message.
Create a test token and run allowed and denied calls
The administrator creates a token for a dedicated test user with only the capability the function needs and links it to the service. The developer calls the function with that token and checks the returned data against the expected result. Then the same call is made with a second test user who lacks the capability, and the check passes only if the response is an access error and no data is returned. Record both results with the token scope, date and tester so the evidence can be reused in the handover.
Document the function for consumers
The developer writes a short reference that lists the function name, service name, parameters with types and required flags, the returned fields, the capability needed, and sample requests and responses from the test calls. The document also states how tokens are issued, rotated and revoked, and which Moodle version the function was tested on. The step is complete when an engineer outside the project can make a successful test call using only the document.
Capability checks, token scope and data exposure risks
A Moodle web service function runs with whatever permissions its caller holds, so the security of an integration depends on how each function checks access, how the service and its tokens are scoped and what data leaves the site. The cards below cover the controls to design and test before any consumer connects.
Check capabilities inside each function
Membership of a service does not prove that a caller may perform an action on a given course or user. Each function should validate the context it operates on and call the capability check for that action, such as require_capability on the relevant context, rather than trusting the service definition. Test with a user who lacks the capability and confirm the call is refused. Review every function for this check during code review.
Scope service membership to least privilege
Only the functions a consumer needs should be added to its service. A service that bundles broad functions makes every token holder a broader attacker target, so split services by consumer where the functions differ. Review the function list each time a new function is added to an existing service, and remove functions that a retired integration no longer uses.
Use dedicated integration users
Tokens should belong to a dedicated user account created for the integration, not to an administrator or a teacher who may leave. That account should hold only the role assignments the functions need, at the site or category level required. Document which account owns each integration so that a password reset, departure or role change does not silently break or over-empower the connection.
Limit token lifetime and rotate tokens
Tokens grant the same access as the account behind them, so a leaked token is a leaked session. Ask whether the chosen Moodle version and token configuration support expiry for the integration, and set a rotation schedule for tokens that cannot expire. Record who issues, stores and revokes each token, and test the revocation path before going live.
Log every web service call
Standard logs may not show which integration called which function with which parameters, so confirm what Moodle records for web service requests and add logging in the function where it does not. Logs should identify the token or user, the function name, the target course or user and the outcome. Send them to your central log store and alert on unusual volume or refused calls.
Return only the fields consumers need
A function that returns a full user or course record may expose email addresses, identifiers, profile fields or grades that the consumer has no need to see. Define the response structure per function, exclude sensitive fields by default and treat each added field as a data-sharing decision. Check responses with a test user from a restricted group to confirm nothing beyond the agreed fields is returned.
How a consumer request reaches a custom function
The request starts in the external system, which sends a token with a web service call to the Moodle site. Inside the trust boundary, Moodle first checks that the token belongs to a service that includes the function, then the function validates its parameters and checks capabilities in the relevant context before any data is read or changed. Check each hand-off, because a missing service membership or an unchecked context is the most common cause of errors and exposure.
Request path from an external system through the Moodle trust boundary to a custom function.
What to document for consumers of a custom function
What should the function name and parameter documentation include?
Document the fully qualified function name exactly as Moodle registers it, the component it belongs to, and the HTTP-free call name the consumer sends in the web service request. For each parameter, record its name, type, whether it is required, its default, allowed values and length limits, and the reason it exists. Parameter definitions in the plugin's db/services.php and the external API class are the source of truth, so the written page should be generated from or checked against them. Include one request example per parameter group so consumers can see how nested structures such as arrays of objects are encoded.
How should return fields be described for consumers?
Describe every field in the return structure with its name, type, whether it can be null or empty, and its unit or format, such as a timestamp in seconds or a code from a fixed list. Explain what each value means in business terms, not only its data type, because consumers build logic on those meanings. State whether the list of results is ordered and whether it is paged, and what a consumer should do when a field is added in a later release. Mark fields that expose personal data so the consumer's own privacy review can account for them.
Which capability and role must the token user hold?
Name the capability string the function checks, the context level where it is checked (system, category or course), and the default roles in Moodle that hold it. Explain that the function's result depends on the user behind the token, so consumers must know which account to create and what it can see. Document any additional checks the function makes beyond the capability, such as enrolment status or group membership. Tell the consumer which service the function is added to and what the dedicated integration account needs, and say that the account should be limited to that service and to the data it requires.
What error responses should the documentation list?
List the exception types and error codes the function can return, with the condition that triggers each one, such as a missing capability, an invalid parameter, or a record the user cannot access. Show a sample error payload for each, copied from a real test call against your Moodle version, so consumers can match it in their code. Explain how errors appear when the token is invalid or the service is not enabled for the user, since those come from the web service layer rather than the function itself. Include guidance on which errors are safe to retry and which indicate a configuration problem.
What versioning and deprecation policy should the document state?
State the version of the function you are publishing and the Moodle release it was tested against, since the Moodle version determines the API surface and the supported environment. Commit in writing to how changes are announced: which changes are additive and non-breaking, which require a new function name, and how much notice a deprecated function receives before removal. Record the minimum supported Moodle version and the date of each change in a changelog. Confirm the notice period and support window with your own owners before publishing, because they are business commitments rather than technical facts.
What test account and sample call should consumers receive?
Provide a dedicated test account with the same role and capability set as the production integration account, on a non-production Moodle site where possible. Include the test site URL, the service name, a way to generate a token for that account, and a working sample call with its expected response. Explain what data the test site contains and that it is synthetic, so consumers do not expect live records. Give a second sample for a negative case, such as a call missing a required parameter, so consumers can confirm their error handling before going live.
Who owns the documentation after the function goes live?
Name the team that maintains the function and the documentation, and the contact that consumers use for questions and change requests. Documentation drifts when the code changes without an update, so tie each release of the plugin to a documentation review in the release checklist. Store the documentation in the same repository as the plugin so changes go through the same review. Agree how long old documentation versions remain available to consumers still on earlier Moodle releases. The ownership and review cadence should be written into the engagement scope so it is not left to individual developers.
Does the documentation need to cover data protection and privacy?
Yes, because a web service function often returns personal data that the consumer then stores or forwards. Document which personal data fields the function returns, the lawful purpose the integration serves as your organization defines it, and any fields that should be excluded from the consumer's logs. Describe how the function fits into Moodle's privacy API, so the data it touches is covered by the site's export and deletion tools. Ask your privacy or legal team to review the wording, since the documentation should reflect your own obligations rather than a general statement.
Limits and what to confirm in your environment
The External API behaves differently across Moodle versions, and the limits that matter most often sit outside Moodle, in your web server, proxy and hosting contract. Each card below is an item to confirm against your own version and environment rather than assume from documentation alone.
Web service and token behavior per version
Confirm how web service enablement, the web service token flow and the service definition screens work in the exact Moodle version you run. Check whether your site uses the /public document root, because from Moodle 5.1 the web server must point to that directory, and a misconfigured root can expose errors or directory listings on the endpoint your integration calls. Test token issuance and function calls on a staging copy before you commit to a design.
How the External API changes across releases
Each major release can change function signatures, deprecate functions or alter the behavior of existing ones, so a function that works today may need changes at the next upgrade. Read the release notes for every version in your upgrade path and list the external functions your integration uses. Plan a regression run of those calls on each target version before the production upgrade.
- Minimum for 5.3 upgrade
- 4.4
Payload and rate limits at the edge
Request size caps, timeouts and rate limits set by your reverse proxy, load balancer or web application firewall often apply before Moodle sees a call. Large batch operations, such as bulk enrolments or grade pushes, can hit these limits in ways that look like Moodle errors. Ask the infrastructure team for the actual body size, read timeout and rate settings on every hop, and test a realistic maximum batch size end to end.
Custom plugin support in your hosting
Managed hosting may not allow you to install local plugins or edit code, which would block a custom function that lives in a local plugin. Confirm with the provider whether you can deploy custom code, which PHP and database versions they offer, and how they handle upgrades. If the platform is self-hosted, confirm the change process and who approves code deployed to the production server.
Moodle plugin typesDatabase and PHP requirements per release
The database engine and PHP version your site runs must match the requirements of the target release, and those requirements change between versions. A new function that depends on a newer database feature or PHP syntax can fail on an older stack. Check the minimum PHP and database versions for each target release and confirm your production stack meets them before you rely on new functions.
- Minimum PHP for 5.3
- 8.3
Questions teams ask before building custom web service functions
How much does it cost to build a custom Moodle web service function?
Cost depends on how many functions you need, how complex their inputs and outputs are, and how much permission logic and testing sits behind each one. You pay for scoping, development, review, testing on your own Moodle version, and documentation for the systems that will call the functions. Ask any provider for a quote that itemizes these components, separates one-time build work from recurring upgrade and support work, and states which Moodle version and external system the quote covers. No supplied figure exists here, so use the written scope as the basis for comparison rather than a per-function rate.
How long does a custom web service function take to build?
Duration follows the number of functions, the depth of the data model they touch, and how many environments must be tested before release. A single read-only function on a well-understood table is a much smaller job than a set of write operations that create users or enrolments and must respect existing capabilities. Ask for a timeline that breaks work into scoping, build, testing against your staging site, and release, and confirm which steps depend on your team making decisions or providing access. No duration is given here because none is supplied for this topic.
What does our team need to provide for the build?
The work needs a named owner for the integration, a written list of the operations the external system must perform, and access to a non-production Moodle site that runs the same version and plugins as production. Your team should also confirm which Moodle roles and capabilities the integration user will hold, who signs off on data exposed through the API, and how the consuming system will store and rotate the token. Without these inputs, function design stalls at the questions that matter most for security.
Can an internal Moodle developer build these functions without outside help?
Yes, if the developer knows Moodle's plugin structure, the External API, and how capability checks and parameter validation work in Moodle core. Building a function means writing a definition in the plugin's db/services.php file, implementing the function class with parameter and return descriptions, and testing it through the web service layer. The harder part is review: a second engineer should check permission logic, data exposure, and error handling before a token is issued. Teams without that experience usually get more value from a short design review than from building the whole set alone.
How do Moodle upgrades affect custom web service functions?
Custom functions live in a plugin, so they survive core upgrades as long as the plugin is maintained for the target Moodle version and core APIs they call still exist. Each major release can change APIs, remove features, or change requirements, so every function should be retested on the staging site before any production upgrade. Moodle 5.1 and 5.3 release notes list the server and database requirements that also affect the test environment, and the upgrade path must be planned from your current version. Keep functions small and dependent on stable core APIs to reduce the cost of each upgrade.
What makes the scope of a web service project grow or shrink?
Scope grows with the number of operations, the number of external systems consuming them, the sensitivity of the data returned, and the number of Moodle roles that need different access. Write operations, bulk operations, and functions that cross course, user, and grade data add review time because each needs careful capability checks and validation. Scope shrinks when the integration can use existing core web service functions, when the consuming system needs only a few read operations, or when the data model is already documented. Agree on the function list and acceptance tests in writing before development starts.
Who is responsible for security reviews of exposed Moodle functions?
Your organization stays responsible for deciding which data an external system may read or change, and for approving the token holder's role and its permissions. A provider can design the capability checks, test parameter validation, and review what each function returns, but independent review may still be needed under your own security policy or compliance assessment. Ask for a written list of tested cases, including unauthorized users, malformed input, and attempts to reach data outside the integration user's scope. DeployOpen does not issue audit reports or certifications, so any formal assurance must come from an independent assessor.
How DeployOpen scopes and delivers Moodle integration functions
DeployOpen approaches custom Moodle web service functions as a fixed-scope engagement inside your own infrastructure. We agree which operations, consumers and capability checks are in scope, build and test the functions against your Moodle version, and hand over documented endpoints your integration team can run and maintain.
How we scope
- Written scope lists each new operation, its consuming system and the Moodle capabilities it must respect
- Scope records the Moodle version and database targets, so function behaviour is confirmed against the release you run
- Scope names the service account, token policy and roles that will call each function
- Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts
How we build
- Functions are written against the External API structure, with parameter definitions and return types declared explicitly
- Every function checks the capabilities and context of the calling user before reading or writing any data
- Input validation and error handling are tested with malformed, out-of-scope and unauthorised requests
- Functions are added to a dedicated service so that only the agreed operations are exposed to consumers
How we hand over
- Each function is documented with its name, parameters, required capabilities, example requests and responses
- Code lives in a version-controlled plugin, with install and upgrade steps written for your administrators
- Test results from the capability and validation checks are delivered with the code
- Knowledge transfer covers how to add a function, rotate tokens and review service logs
How we support
- Ongoing support, Moodle upgrade checks and continuous testing are available as retainers
- Retainers cover re-testing functions when a Moodle minor or major release changes related core code
- Support can include reviewing new consumer requests against the agreed scope before they are built
- Confirm response times, coverage and exclusions in the written retainer before signing

