Views: 3588
Last Modified: 18.01.2022

You can make controllers, programmed inside a module, available for REST module. This is very convenient, because we re-use already written code.

You need to correct .settings.php module config.

Important! This is a new method that requires dependency from REST 18.5.1).

<?php
return [
	'controllers' => [
		'value' => [
			'defaultNamespace' => '\\Bitrix\\Disk\\Controller',
			'restIntegration' => [
				'enabled' => true,
			],
		],
		'readonly' => true,
	]
];

How to use \CRestServer in AJAX-action

In case AJAX-action must use \CRestServer for a specific task, it can be done by declaring \CRestServer as one of parameters.

Example:

public function getStorageForAppAction($clientName, \CRestServer $restServer)
{
	$clientId = $restServer->getClientId();
	...
}

Please, be advised, the example above cannot work via standard AJAX, because \CRestServer $restServer is not available in it and cannot be implemented. It can be available only for the REST module. If you declare it as optional, everything will work.

public function getStorageForAppAction($clientName, \CRestServer $restServer = null)
{
	if ($restServer)
	{
		$clientId = $restServer->getClientId();
	}
	...
}

How to understand, if actions are called in REST or AJAX environment?

It can happen that you need to distinguish in which context the action is presently executed: in REST or AJAX? You need to ask the controller:

\Bitrix\Main\Engine\Controller::getScope()

//possible variants
\Bitrix\Main\Engine\Controller::SCOPE_REST
\Bitrix\Main\Engine\Controller::SCOPE_AJAX
\Bitrix\Main\Engine\Controller::SCOPE_CLI




Courses developed by Bitrix24