custom API endpoint, should I put it to local plugin ?

custom API endpoint, should I put it to local plugin ?

by Fauzan Hibatulah Ashari -
Number of replies: 1

Hello, I am developing moodle block, it will GET data from my custom API every time javascript event is occurred. The code bellow is my API with.

// file: /var/www/html/MOODLE/custom_api.php

<?php

$sql = "SELECT  * FROM mdl_*******";

return $DB->get_records_sql($sql);

..............................


I know it is not moodle best practice approchment, any suggestion to make it better ? Should I create my local plugin or create lib.php to my block folder ?

Thanks in advance

Average of ratings: -
In reply to Fauzan Hibatulah Ashari

Re: custom API endpoint, should I put it to local plugin ?

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
The very first thing you should do is fix the SQL statement.

Using "mdl_" in an SQL statement will completely break on any site that uses any other prefix (which includes and sites set up to run PHPUnit or Behat tests) - for Moodle SQL statements, always wrap the table name in { and } - e.g. "SELECT * FROM {user}" (NEVER write "SELECT * FROM mdl_user"). But, even better, in this case, just write $DB->get_records("tablename", []) - where tablename is the name of the table without the 'mdl_' prefix. Have a good read through of the Moodle data manipulation API documentation.

After you've got the DB query sorted out, the next step would be to move everything into a local plugin, turn your handler into a webservice then rewrite your javascript code to call this via the AJAX api. All of this is quite a bit of work (especially for someone new to Moodle development), but will, in the end, give a good solid base for further development.