Available right now in the form of the WordPress REST API Plugin, the goal of the project is to enable predictable, resource-oriented URLs, standardized return structures and to use HTTP response codes to indicate API errors.

In this article I’ll take a look at the basics of the REST API (WordPress RESTful API) and how you can use it right now to make your website or web application that much better.

WordPress Rest API Basics

Once you’ve downloaded and activated the plugin your site is ready to go and your API base path will be /wp-json/. This means that to get all your posts from an external application you can make a request to http://yoursite.com/wp-json/something.

In most cases the “something” in the URL will start with /wp/v2 which indicates that you are using version 2 of the API

The easiest way to try out the new API is to make sure you’re logged in to the website you’ve installed and activated the plugin on and visit a route. Check out http://yoursite.com/wp-json/wp/v2/posts for example.

WordPress REST API Screenshot

If you see a response but it’s just a mass of text, I recommend using the JSON Formatter for Chrome or JSONView for Firefox.

HTTP Verbs

REST APIs use HTTP Verbs which determine the type of action a client may want to perform. HEAD, GET, POST, PUT, and DELETE can be used which are standard across the web.

HEAD is used to retrieve HTTP header information, GET retrieves information about a resource, POST creates a resource, PUT updates a resources and DELETE deletes a resource. Resources are discreet entities in WordPress such as posts, comments, users and so on.

Routes And Endpoints

Endpoints are specific functions that can be reached by sending the appropriate HTTP verb to the appropriate URL. The route is the URL itself, the endpoint is the combination of the route and the type of action used.

/wp/v2/posts/342 is a route which has three endpoints. Using GET will retrieve the resource, using PUT (along with parameters) can update the resource and DELETE will delete it.

Using the WordPress Rest API

From here on out you can do almost anything you could on WordPress proper. You can create posts, update users, moderate comments – all this from any other application you want. It’s a matter of knowing the routes, endpoints, the schema and parameter requirements. The main page of the API Documentation has plenty of information for you regarding these.

If you need a list of all available routes you can simply send a GET request to /wp/v2/. This has the added benefit of listing all routes and endpoints available to your site specifically – since you do have the option of adding your own.

Authentication

The first thing you’ll want to tackle is authentication – granted, this is a bit difficult. Once you’ve figured it out, the rest is a breeze though. Right now there are three types available:

  • Cookie Authentication – For plugins/themes running on the same site
  • OAuth – For external clients
  • Basic Authentication – For testing only

I’m going to recommend basic auth for the purposes of learning, but please do not use it in the wild – it isn’t very safe at all.

To get started you’ll need to install the Basic Auth plugin. The plugin is only available via Github, you can install it by downloading the zip and installing the zip file in the plugins section.

To demonstrate how to access a WordPress installations API I am going to write some PHP code on my localhost which will access the metadata of a post on my actual website.

To grab publicly available data you can use the wp_remote_get() function, here’s how:

$response = wp_remote_get( 'http://danielpataki.com/wp-json/wp/v2/posts');

By printing out the $response variable you’ll see a bunch of data, including the list of posts. If you try the same method for a restricted resource you’ll bump into an error which reads: “Sorry, you cannot view the meta for this post”. Here’s where authentication comes in.

Using basic auth we can send our username and password along for each request which will grant us the proper privileges.

$response = wp_remote_get( 'http://username:password@danielpataki.com/wp-json/wp/v2/posts/445/meta');

This call will be successful, I’ll be able to see all the post meta associated with post 445. The drawbacks of this method should be apparent.

You need to send your username and password with each request and – worst of all – as plain text! Just to recap: this is fine for testing and learning about the API but never use this in production.

Looking for ways to improve your WordPress development workflow?

Kinsta’s hosting solution was built by developers for developers. Git, PHP 7, SSH, and WP-CLI, along with powerful staging and cloning environments gives you the tools you need to build sites faster!

Sending Data

Getting resources is pretty obvious. You use the GET verb on the proper endpoint and you get back a mass of JSON which you can work with in Javascript directly, or you can use json_decode() in PHP to convert it to an array. How about more complex procedures where we send data, often with parameters. The example below creates a post via the REST API.

$args['body'] = array( 'title' => 'API TEST', 'status' => 'draft', 'content' => 'content'
);
$response = wp_remote_post( 'http://username:password@danielpataki.com/wp-json/wp/v2/posts/', $args );

Knowing what to add to the request body is a matter of glancing at the schema. It contains the parameter names, the data types, the description and context.

The response contains a bunch of information about our new post, including the ID, which could come in handy if we want to manipulate the postmeta once we’ve added the post itself.

Overview

I hope this quick primer has shown how easy it is to work with the JSON API. It’s final inception into the core (hopefully soon) will take existing apps to the next level and will allow developers to create mobile clients for complex websites running WordPress.

In an upcoming article, we’ll look at the JSON API in more detail, including more complex forms of authentication and custom endpoints, stay tuned!

Similar Posts