Introduction to WordPress REST API

|
| By Webner

WordPress REST APIs – Introduction and Example

What is an API?

API stands for Application Programming Interface. It is a piece of software that works as a bridge between two different applications.

For example suppose you have to post something on facebook from a third party program then you will use the facebook APIs to post there.

What is REST?

REST stands for Representational State Transfer. It is the language-independent architectural style based upon certain set of principles that describe how the networked resources are defined and addressed. It is an HTTP-based style of building the APIs that is:
a) lightweight
b) suitable for high data volume
c)highly compatible
d) user friendly

What is WP REST API?
WP REST API intends to make a connection between wordpress and other software applications which can be characterized by the universality and high compatibility.

So it provides us an easy-to-use set of HTTP endpoints that let us access the site’s data in simple JSON (JavaScript Object Notation) format, including users, posts, taxonomies and more. Hence retrieving or updating data is as simple as sending a HTTP request.
The WP REST API is revolutionary as it allows WP to connect with other websites and services, no matter in which language they are written in. You will get all in JSON format, which is easy to use.

Built-in wordpress REST APIs

There are so many built-in WP REST APIs to retrieve users, posts, taxonomies.
Few of them are listed below here
POSTS – /wp/v2/posts
CATEGORIES – /wp/v2/categories
TAGS – /wp/v2/tags
PAGES – /wp/v2/pages
TAXONOMIES – /wp/v2/taxonomies
MEDIA – /wp/v2/media
USERS – /wp/v2/users

But we can create our custom WP REST APIs by creating custom API endpoints (function, module or method).

Let’s take an example
So here in this example, this is my API endpoint which I’m calling for post title written by a specific author by using author ID.

function test_api_fun(  )
{
$api_response=’Call to API endpoint successful’;
return $api_response;
}

So to make this available via API we need to register a route for this endpoint.
This can be done through a function that is register_rest_route, and this should be called in a callback on rest_API_init, so that it can be accessible on API load.

add_action( 'rest_api_init', function () {
 register_rest_route( '/custom_api', '/test_api', array(
   'methods' => 'GET',
   'callback' => ‘test_api_fun’,
 ) );
} );

The three parameters that we have passed to register_rest_route(‘’,’’,’’) are namespace, route and the options.

So if our site domain name is ‘test_example’ then the API endpoint route will be http://test_example.com/wp-json/custom_api/test_api. When we hit this from our browser it will give us the value returned by test_api_fun().

Leave a Reply

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