Create a custom REST endpoint in WordPress[1 example]
When you want to use WordPress as a headless CMS for your project. Then you must know about the REST APIs. Let’s see how you can create a custom REST endpoint in WordPress.
Table of Contents
What is REST API?
REST stands for Representational state transfer and API stands for Application Programming Interface.
A software architecture called Representational State Transfer (REST) places restrictions on how an API should operate. In the beginning, REST was developed as a set of rules to control communication on a complicated network like the internet.
To facilitate high-performing and dependable communication at scale, employ a REST-based architecture. It is simple to implement and adapt, giving any API system visibility and cross-platform compatibility.
Developers of APIs can create APIs using a variety of architectures. REST APIs are APIs that adhere to the REST architectural design. RESTful web services are online services that use the REST architecture.
RESTful web APIs are commonly referred to as RESTful APIs. REST API and RESTful API can, however, be used interchangeably.
When you want to communicate between two applications, you can do it with API. Whether it is Web to Web communication, Web to Mobile communication, or other software systems.
Create a custom REST endpoint
It is very easy to create a REST endpoint in WordPress with WordPress’s default function.
We can use the register_rest_route() function to register our custom route. Let’s see the example.
function create_custom_endpoint(){
register_rest_route(
'wp/v2',
'/custom-ep',
array(
'methods' => 'GET',
'callback' => 'get_response',
)
);
}
You can define your needed response in your callback function. So we have to create one more function get_response.
function get_response() {
// Add your data
$data = [
'name' => 'Krupal',
'surname' => 'Panchal',
];
return $data;
}
Now add the function on rest_api_init
hook.
add_action( 'rest_api_init', 'create_custom_endpoint' );
Output: