How to Get Custom Posttype Data in WordPress by API KEY via REST API

How to Get Custom Posttype Data in WordPress by API KEY via REST API

I decided to slightly complicate our previous code by adding a simple API KEY access check. The example below demonstrates the most basic implementation of access control via a key. In real applications, it is recommended to use something more advanced, like access validation via a Bearer token.

<?php
add_action('rest_api_init', function()
{
	/**
	 * Get
	 */
	register_rest_route('app/v1', 'get', [
		'methods' => WP_REST_Server::READABLE,
		'permission_callback' => function(WP_REST_Request $Request)
		{
			if($Request -> get_param('key') != '123qwe')
			{
				return new WP_Error('key', 'API KEY is wrong', [
					'status' => 400
				]);
			}

			return true;
		},
		'callback' => function(WP_REST_Request $Request)
		{
			$Post = get_post( $Request -> get_param('post_id') );
			if(is_a($Post, 'WP_Post'))
			{
				return $Post;
			}
			return [];
		},
		'args' => [
			'key' => [
				'description' => 'API KEY',
				'type'=> 'string',
				'required' => true,
			],
			'post_id' => [
				'description' => 'Post ID',
				'type'=> 'integer',
				'required' => true,
			],
		]
	]);
});

Let’s break down the code in more detail. In the “permission_callback” key’s callback, we perform API key validation:

'permission_callback' => function(WP_REST_Request $Request)
{
	if($Request -> get_param('key') != '123qwe')
	{
		return new WP_Error('key', 'API KEY is wrong', [
			'status' => 400
		]);
	}

	return true;
},

If the method “$Request -> get_param('key')” returns the value “123qwe”, the validation will pass successfully, and WordPress will automatically proceed to execute the anonymous function in the “callback” key:

'callback' => function(WP_REST_Request $Request)
{
	$Post = get_post( $Request -> get_param('post_id') );
	if(is_a($Post, 'WP_Post'))
	{
		return $Post;
	}
	return [];
},

Here, using the GET variable “post_id”, we retrieve the post data, check its object type, and if it’s a “WP_Post”, we return the post data as a JSON string. Otherwise, an empty array is returned, which also translates to an empty JSON array.

Note that we slightly simplified our work by adding basic validation through the “args” array:

'args' => [
	'key' => [
		'description' => 'API KEY',
		'type'=> 'string',
		'required' => true,
	],
	'post_id' => [
		'description' => 'Post ID',
		'type'=> 'integer',
		'required' => true,
	],
]

This makes the “key” and “post_id” parameters required. Additionally, “post_id” must be a number.

That's all.

Posts on similar topics

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *