Application program interface or in short API is one of the important thing that every developer probably have used once or more for their projects. WordPress is also known well for it’s Rest API development features. Today, we will learn the basics of Rest API, it’s usages and later we will learn how do we create our own custom Rest API route in WordPress.
What is Rest API in WordPress
Rest API provides us the way to match URIs to various resources in our WordPress install. Like if we have pretty permalinks active, the default WordPress Rest API lives at /wp-json/
. We can access Rest APIs index by making GET requests. For example, if we have a WordPress site http://example.com
, we can access the Rest API index by making a GET request to http://example.com/wp-json/
. This will provide us the available routes.
Routes and Endpoints
Endpoints are functions available through APIs. It can be used for purpose like create posts, read posts, update posts or delete posts. In short this method is known to us as CRUD. On other hand, route is the “name” we use to access the endpoints.
For example, if we access this posts itself here https://templateartist.com/wp-json/wp/v2/posts/52
, we can see the JSON of this post. Here the route is “wp/v2/posts/52
“. Route does not include wp-json
because wp-json
is the base path for the API itself. We should not change the base path itself. Now, this route has several endpoints like read, update or delete. We will not make it complex for you now as we will stick to the route creating process.
Create a custom rest api route
Route in WordPress are presented by URIs as we see in the above example. A route contains basically two parts. First part is called the namespace which is wp/v2
in this case. This is basically works as identifier or prefix. The v2
in this case is the version number of the API route. Now, the second part is the name in which we wish to return the actual JSON code. Like the default posts
returned by this name. This part always should be unique. If we have a custom post type “books“, we can create the route like “mycpt/v1/books
“.
We need to register our custom route by using the WordPress function name register_rest_route()
. This function accepts 4 parameters which are $namespace
, $route
, $args
, $override
. The first two parameters are required while the other two are optional. Let’s take a live example and then see what it does.
/**
* rest API
* custom route for books
*/
//adding the function to this action
add_action('rest_api_init','tartist_register_book_api');
//the function for registering API
function tartist_register_book_api(){
register_rest_route('tartist/v1','books',array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'tartist_books_result'
));
}
//the callback function
function tartist_books_result(){
$books = new WP_Query( array(
'post_type' => 'books',
'posts_per_page' => 10
) );
$book_results = array();
while( $books->have_posts() ) {
$books->the_post();
array_push( $book_results, array(
'title' => esc_html( get_the_title() ),
'permalink' => esc_url( get_the_permalink() ),
'image' => esc_url( get_the_post_thumbnail_url(0, 'medium_large') )
) );
}
return $book_results;
}
In the above example code, we are registering custom route for books and getting custom JSON data as per our need. So the unnecessary data will not be returned to save fetch time. Here tartist/v1
is the first parameter for $namespace
, the books
is the second parameter $route
and the array()
is the third parameter $args
. Note that we haven’t used the fourth parameter as that is basically a boolean to override an already existing route. That we don’t need.
Now, notice the third parameter we used is array with two arguments. First is 'methods' => WP_REST_SERVER::READABLE
this is basically we are telling WordPress about the purpose. In this case we are going to read the book posts. The second one is 'callback' => 'tartist_books_result'
which we are using as callback function and later defined the callback function and returned some specific data from book post type posts.
Where to use this code
You can simply use this code inside your theme’s function.php or the best way to do this is create a custom plugin and place the code there. This way everything will be organised.
Imagine you want to display live search results. This method can save you a lot of time with simple jQuery Ajax call and then you can fetch data as needed. I have used exactly same thing in our latest Xgenie – Business Portfolio Theme. I will make a tutorial about that later.
Let me know if you have any questions on this topic.