tschaki
create wordpress plugin
Home » Extend WordPress REST API

Extend WordPress REST API

Every WordPress website has an API interface by default with various endpoint. This is dynamically extensible via, for example, a plugin or theme. With each newly added endpoint, a function can be executed and a value can be output.

What WordPress REST API is for

The already existing REST API is ideally suited to read out custom post types, for example, with all the posts contained therein. Filtering options are also available via URL.

To get to the API interface overview, the URL call looks like this: https://tschaki.com/wp-json/

In this post we will cover the dynamic extension of the interface with POST and GET requests.

Add new API endpoint for POST

If a new endpoint is defined via POST, it cannot be retrieved as, for example, GET. This would result in a 404 error. POST is a great way to pass user data to the API in a hidden way. Callback is best suited to place additional functions. For example, when used for database entries.

// Register new WP REST API Endpoint.
add_action( 'rest_api_init', function ( ) {
    register_rest_route( 'namespace', 'apicall', array(
        'methods' => 'POST',
        'callback' => 'api_call'
    ) );
} );

// Callback for new API Endpoint Call.
function api_call( WP_REST_Request $request ) {
    $request_params = $request->get_params( );
  	return $request_params['param']; // returns "sended_param" on success.
}

Passed POST variables by jQuery Ajax are to be read as parameters in the callback. These are created in an object.

In this example Javascript jQuery snippet, the new WordPress API endpoint can be called via an Ajax request.

jQuery.ajax({
	method: "POST",
	timeout: 5000,
	async: true,
	url: "/wp-json/namespace/apicall",
	data: {param: 'sended_param'},
	error: function() {
		console.log( "failed" );
	}
}).done(function ( msg ) {
  	// Maybe markup manipulation.
});

Add new endpoint for GET

As a GET endpoint, the only thing that falls away is the ability to attach a jQuery data: {} object to be appended.

// Register new WP REST API Endpoint.
add_action( 'rest_api_init', function ( ) {
    register_rest_route( 'namespace', 'apicall', array(
        'methods' => 'GET',
        'callback' => 'api_call'
    ) );
} );

// Callback for new API Endpoint Call.
function api_call( ) {
  	return true; // returns "true" on success.
}

Also in this case the WordPress REST API endpoint must be called as GET. As POST this results in code 404.

jQuery.ajax({
	method: "GET",
	timeout: 5000,
	async: true,
	url: "/wp-json/namespace/apicall",
	error: function() {
		console.log( "failed" );
	}
}).done(function ( msg ) {
  	// Maybe markup manipulation.
});

Source: WordPress Codex

Trent Bojett

My name is Trent Bojett, I am 28 years old and I live in Switzerland. Because of my enthusiasm for writing and the logical world (= software development) I started this blog in early 2020.

Add comment