EDIT: I've managed to solve this myself, by looking around the forums and seeing what is done for people creating threads and users via "external" scripts. My solution is:
function GetAPIKey() {
$dir = $_SERVER["DOCUMENT_ROOT"];
require("$dir/src/XF.php");
XF::start($dir)...