Site icon WebDevStudios

An Overview of the WordPress JSON API

** UPDATED POST FOR WP-API V2 HERE

WordPress has had no formal REST API. There is the crude XMLRPC, but we won’t go into the gory details of the past.

As part of Google Summer of Code (GSOC), Ryan McCue submitted a proposal for creating a formal JSON API to be included in WordPress core and therefore available to every WordPress.org install.

For those who may not know what a REST API is; it stands for Representational State Transfer. In short, it separates client from the server. Each request from any client contains all the information necessary to service the request, and session state is held in the client.

There is no “official” standard for RESTful web API’s. This is because REST is an architectural style. You can use HTML, XML or JSON. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write, it’s very easy for machines to parse and generate. This is largely in part the reason it has become the de facto choice when creating REST API’s, and also the reason JSON data is the response format of the forthcoming API.

JSON API OVERVIEW

Currently, you can use the WordPress JSON API on your site via a plugin you install from the WordPress repository; the functionality in this plugin will eventually be included in the core WordPress software. Activate it and you now have a REST API for your site’s content. The plugin exposes your data in JSON format in the following content types:

The response data is like what you would get in the WordPress loop, only the format is JSON. This allows you to display it in any way you wish. You can even filter the API calls in a similar fashion to the loop.

Want to get your site’s posts? Simply send a GET request to url.com/wp-json/posts. Update user with ID 4? Send a POST request to url.com/wp-json/users/4. Get all posts with the search term “awesome”? GET url.com/wp-json/posts?filter[s]=awesome. It’s that easy.

Let’s look at some of the JSON responses from WP-API developer @RachelBaker‘s site:

This is just a small example of the wide range of data you are able to request from the API.

Some API calls require authentication, just like WordPress requires authentication to access wp-admin, or to create new posts. Most GET requests do not require authentication, this allows you to display content via the API on the front of your site, or in an external app without a user needing to log in.

Here is an example AJAX call to filter the posts API endpoint response:

$.ajax({
    url: 'http://url.com/wp-json/posts',
    data: {
        filter: {
        'posts_per_page': 5
        }
    },
    dataType: 'json',
    type: 'GET',
    success: function(data) {
        // success code
    },
    error: function() {
        // error code
    }
});

Most anything you can filter get_posts you can use to filter the posts JSON response. The other API endpoints are filtered in much the same way.

Also, you can use authenticated API calls to PUT or DELETE content. To edit a post you send a PUT request to the API at url.com/wp-json/posts/id where id is the post id you wish to edit. To add meta to a post send a Post request to url.com/wp-json/posts/id/meta and in your ajax supply a key and value in the data parameter. This really could not be any more simple.

In a lot of cases, people choose WordPress as their CMS because it’s very easy to add new content types. Another benefit of the JSON API is it works well with Custom Post Types (CPT). To access a CPT you add a type parameter to the API request (url.com/wp-json/posts?type=cpt); and you can add any other get post filters as well.

There is one gotcha with posts, and that is custom meta, it’s not added for you. If you want to include custom meta it is easy to add with a filter to json_prepare_post.

Example function to add meta to posts:

function custom_json_api_prepare_post( $post_response, $post, $context ) {

    $meta = get_post_meta( $post['ID'] );
    $post_response[‘meta_field_name’] = $meta;

    return $post_response;
}
add_filter( 'json_prepare_post', 'custom_json_api_prepare_post', 10, 3 );

There is also some great documentation for the API, read through them and even check out issues on Github to get a better handle on current state of the API.

API USAGE

You may be asking why you need a JSON API in WordPress. There are many reasons, but the main reason is to allow access to data without any constraints on its usage. This allows developers to create unique experiences, one of them being custom applications. Also, plugins and themes can access the data on your site and display the content more efficiently than reloading the entire page. Sections of a site can be updated live or with user interaction.

Maybe you have a Multisite install, and each site is a store. You may want to display all of the sales items from each site on the network that are tagged “Halloween”. The API makes these types of data mash-ups very easy to implement.

Maybe you want to post to your WordPress site from a web connected device. Smart devices are gaining momentum, apps from these devices can access your API, and your site will handle the request.

I could list a hundred more ideas for usage but the point of why we need and API in WordPress is this…

If every WordPress site is running a similar API data structure, and the sites data is open, amazing things can be created.

This post is the first in a series where I will go deeper into all aspects of the API, keep an eye out.

Some Additional Resources Worth Checking Out

http://wp-api.org
https://wordpress.org/plugins/json-rest-api
http://apppresser.com/using-wordpress-rest-api-mobile-app
http://wordpress.tv/2014/07/06/rachel-baker-put-your-content-to-rest-with-wp-api
http://wordpress.tv/2014/10/13/andrew-nacin-post-modern-wordpress

Exit mobile version