Як до WordPress додати свій REST API Endpoint

Як до WordPress додати свій REST API Endpoint

Як було написано в попередніх статтях, WP має багатий функціонал з коробки для роботи з його API. Сьогодні ми розглянемо код створення власного endpoint'а для зчитування даних.
Для мінімальної реалізації свого API у WordPress нам знадобиться екшн “rest_api_init” і функція “register_rest_route”.

Спочатку весь код:

add_action('rest_api_init', function()
{
	/**
	 * Read
	 */
	register_rest_route('app/v1', 'read', [
		'methods' => WP_REST_Server::READABLE,
		'permission_callback' => function(WP_REST_Request $Request)
		{
			//Sets
			$test_string = $Request -> get_param('test_string');

			if(empty( $test_string ))
			{
				return new WP_Error('test_string', 'Field test_string is required', [
					'status' => 400
				]);
			}

			return true;
		},
		'callback' => function(WP_REST_Request $Request)
		{
			$test_string = $Request -> get_param('test_string');
			$test_integer = $Request -> get_param('test_integer');
			$test_enum = $Request -> get_param('test_enum');
			$test_array_integer = $Request -> get_param('test_array_integer');

			
			return [
				'test_string' => $test_string,
				'test_integer' => $test_integer,
				'test_enum' => $test_enum,
				'test_array_integer' => $test_array_integer,
			];
		},
		'args' => [
			'test_string' => [
				'description' => 'Some test string',
				'type'=> 'string',
			],
			'test_integer' => [
				'description' => 'Some test integer',
				'type'=> 'integer',
				'sanitize_callback' => 'absint',
			],
			'test_enum' => [
				'description' => 'Some test enum',
				'type' => 'string',
				'enum' => ['yes', 'no'],
				'required' => true,
			],
			'test_array_integer' => [
				'description' => 'Some test array integer',
				'type' => 'array',
				'items' => [
					'type' => 'integer',
				],
				'default' => [],
			],
		]
	]);
});

Як ви, мабуть, здогадалися, для роботи з будь-яким API WP, потрібно обгорнути наш код у хук:

add_action('rest_api_init', function()
{
	/**
	 * API code here
	 */
});

Ядром нашого коду є core-функція WordPress “register_rest_route”, яка власне і реалізує наш endpoint. На вхід функція приймає чотири параметри:
$namespace — перша частина вашого URL маршруту.
$route — друга частина маршруту, може містити регулярні вирази.
$args — масив параметрів для endpoint'а.
$override — чи потрібно перезаписати, якщо маршрут вже існує.

Детальніше розглянемо третій параметр ($args). У нашому прикладі ми використовуємо чотири ключі:
methods — визначає тип запиту (GET, POST, PUT, DELETE).
permission_callback — функція, яка викликається до основної, використовується для перевірок (напр. чи є користувач автором).
callback — основна функція, яка реалізує логіку endpoint'а.
args — масив змінних запиту, їх валідація та допустимі значення.

Наприклад, у “permission_callback” можна реалізувати власну валідацію:

'permission_callback' => function(WP_REST_Request $Request)
{
	//Sets
	$test_string = $Request -> get_param('test_string');

	if(empty( $test_string ))
	{
		return new WP_Error('test_string', 'Field test_string is required', [
			'status' => 400
		]);
	}

	return true;
},

У наведеному коді ми перевіряємо, чи має змінна $test_string значення. Якщо вона порожня, повертаємо помилку й API завершує виконання.

У “callback” ми просто повертаємо отримані змінні, хоча тут можна реалізовувати будь-яку іншу логіку:

'callback' => function(WP_REST_Request $Request)
{
	$test_string = $Request -> get_param('test_string');
	$test_integer = $Request -> get_param('test_integer');
	$test_enum = $Request -> get_param('test_enum');
	$test_array_integer = $Request -> get_param('test_array_integer');

	
	return [
		'test_string' => $test_string,
		'test_integer' => $test_integer,
		'test_enum' => $test_enum,
		'test_array_integer' => $test_array_integer,
	];
},

У підключі “args” перелічуються всі змінні GET/POST, які ми плануємо використовувати:

'callback' => function(WP_REST_Request $Request)
{
	$test_string = $Request -> get_param('test_string');
	$test_integer = $Request -> get_param('test_integer');
	$test_enum = $Request -> get_param('test_enum');
	$test_array_integer = $Request -> get_param('test_array_integer');

	
	return [
		'test_string' => $test_string,
		'test_integer' => $test_integer,
		'test_enum' => $test_enum,
		'test_array_integer' => $test_array_integer,
	];
},

Хоча, що цікаво, через:

'args' => [
	'test_string' => [
		'description' => 'Some test string',
		'type'=> 'string',
	],
	'test_integer' => [
		'description' => 'Some test integer',
		'type'=> 'integer',
		'sanitize_callback' => 'absint',
	],
	'test_enum' => [
		'description' => 'Some test enum',
		'type' => 'string',
		'enum' => ['yes', 'no'],
		'required' => true,
	],
	'test_array_integer' => [
		'description' => 'Some test array integer',
		'type' => 'array',
		'items' => [
			'type' => 'integer',
		],
		'default' => [],
	],
]

можна звернутися і до змінних, які не описані у “args”. Але вони не будуть проходити через фільтри і валідацію.

Як бачите, створити власний Endpoint у WordPress досить просто, особливо якщо заглядати в документацію та читати код WP.
Успіхів!

$Request -> get_param('test_xxx');
Пости на схожі теми

З вашим WordPress сайтом проблеми? потрібний додатковий функціонал? нестандартний плагін чи згорнути нову сторінку?
Тоді напишіть мені через форму зворотного зв'язку, і я намагатимусь вам допомогти.

Напишіть коментар

Ваша e-mail адреса не оприлюднюватиметься. Обов’язкові поля позначені *