Home » C# » WordPress » WordPress Custom Rest API – Adding Endpoints

WordPress Custom Rest API – Adding Endpoints


Adding WordPress Custom Rest API Plugin

Sometimes you prefer to create a custom Rest API in PHP within the context of WordPress to return data in a structured format such as JSON which involves setting up custom routes. Here’s a step-by-step guide to creating & integrating a basic WordPress Custom REST API in a WordPress plugin.





Set up a WordPress Plugin


Go to ‘wp-content/plugins’ directory of your WordPress and create a PHP file (e.g., CustomApi.php) to serve as a main plugin file.

cpanel – File Manger:
custom wordpress rest api plugin php file

In this example, the plugin folder and PHP file names are the same. You can rename it.

You can follow simple 3 steps to create and activate a Custom Plugin in the WordPress Dashboard in a few minutes, check this link – How to Create Custom WordPress Plugin: 3 Easy Steps.


Note:
You can use the function.php file but it’s best practice to use a separate Plugin for Custom API.



Define WP API Route:


In your plugin file, use the add_action function to hook into WordPress and register your custom API route. Here’s an example of how to add an API route:

.php file:
function registe_api_routes() {
    register_rest_route('PublicAPIs/v1', '/GetTop10Items',
						array('methods' => 'GET', 'callback' => 'CallFun_GetTop10Items',)
						);
}

add_action('rest_api_init', 'registe_api_routes');



Parameter Description:
ParametersInputs
NamespacePublicAPIs/v1
EndpointGetTop10Items (Public URL)
https://yourdomain.com/wp-json/PublicAPIs/v1/GetTop10Items
MethodGet method
callback function nameCallFun_GetTop10Items
(Internal method that executes and sends back responses)



Create API Callback Function


Define the callback function you specified in the register_rest_route for your API route. This function will handle the request and return the data you want to show via the API.

In our example, whenever public API is called by an external source then the below code will be executed internally.

.php file:
function CallFun_GetTop10Items() {
	// Your API logic here
	// Example:
	$args =  array('showposts' => 10, 'orderby' => 'post_date', 'order' => 'DESC','post_status' => 'publish');

	$query_result = query_posts($args);

	$postList = [];

	foreach ($query_result as $result) {
	  $postList[] = array( "post_title" => $result->post_title, "post_name" => $result->post_name);
	}

	return $postList;
	// or
	// return new WP_REST_Response($postList, 200);
}


.php code file – screenshots:

Method 1:
create wordpress rest api callback function and register routes

You can write the same code in a shorter way.
Method 2:
create wordpress rest api callback function and register routes method 2



Test Your API Endpoint


You can now access your API endpoint and check if it is working as accepted.


How to find WP API endpoints or URLs?

  • Open the browser and open the Inspect element developer tool as well. (press f12 or right-click & click Inspect)
  • Go to https://yourdomain.com/wp-json/ to get wp-json list.
  • Once it is loaded, navigate and go to routes
  • expand and go to the path (namespace/endpoint) that is defined in register_rest_route method, that is ‘PublicAPIs/v1/GetTop10Items
  • Get the API (full URL) as shown in the below screenshot.
    example: https://yourdomain.com/wp-json/PublicAPIs/v1/GetTop10Items

find wp rest api list wp-json


Test WP Web API – Get Method()

Get API can be executed directly on the browser but for demo purposes, we will use the Postman tool to test our API.

The below screenshot demonstrates that a Get API request sends back a response as a JSON result via Postman tool.

Test API: https://yourdomain.com/wp-json/PublicAPIs/v1/GetTop10Items

wordpress api get posts:
wordpress rest api response result



Calling WordPress Custom Rest API from Javascript


You can use the fetch method in Javascript to call and get the response from the WordPress Custom Rest API, as demonstrated below.

<script>

document.addEventListener("DOMContentLoaded", LoadLatestPosts);

async function LoadLatestPosts() {

	const response = await fetch('/wp-json/PublicAPIs/v1/GetTop10Items');
	const data = await response.json();

	data.forEach(obj => {
		// your logic
	});

}

</script>

Note:
You might get an error if the full URL is given with the domain name, so specify the internal URL in the fetch method as mentioned in the code.



for more details check this link: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

Leave a Reply

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