WordPress REST API Quickstart

The WordPress REST API has been available since 4.7.  It’s robust, consistent, and nifty to work with. Why? Backend and mobile developers can use other frameworks while still keeping WordPress around for their customers. Frontend developers can build sites using JavaScript without having to touch PHP. Up is down, left is right, dogs and cats living together… Let’s get started!

Recommended Tools

Troubleshooting

  • JSON Formatter: CTRL/CMD+Click a triangle to collapse/expand nodes at the same level.
  • YARC: When testing with Basic Authentication, make sure you are logged out of WordPress first.

Getting Started

WP API supports all HTTP Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS.

WP API respects permissions but the developer must setup authentication separately.

Schema

WP API is self-documenting. Send an OPTIONS request to any endpoint and get back JSON Schema compatible info on how to use it:

OPTIONS

To get the entire API schema in a single query, add context=help at the index. (Ie. http://site/wp-json?context=help )

Features

WP API items have a _links node based on HAL (Hypertext Application Language):

_links

To reduce the number of HTTP requests use the _embed parameter to tell the API that the response should include embeddable resources.

_embed

WP API exposes pagination info in the response header.

Pagination

PHP to JSON

WP API renders JSON in a generic way that does not match the DB columns. Keep calm and RTFM:

if ( ! empty( $schema['properties']['author'] ) ) {
    $data['author'] = (int) $post->post_author;
}
if ( ! empty( $schema['properties']['slug'] ) ) {
    $data['slug'] = $post->post_name;
}
if ( ! empty( $schema['properties']['content'] ) ) {
    $data['content'] = array(
        'rendered'  => post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content ),
        'protected' => (bool) $post->post_password,
    );
}
{
  "author": 1,
  "slug": "chapter-1",
  "content": {
    "rendered": "<p>Hello World!</p>",
    "protected": false
  }
}

Example

Setup the Basic Authentication Plugin on your development environment.

In YARC, add your credentials:

YARC CredentialsSend an OPTIONS request to a post endpoint. The response will contain, among other information:

 {
   "methods": [
     "POST",
     "PUT",
     "PATCH"
   ],
   "title": {
     "required": false,
     "description": "The title for the object.",
     "type": "object"
   },

Translation: The API client can send a PUT request to change the title.

In YARC, send a PUT request with the following JSON to the endpoint:

{ 
  "title": "My changed title!" 
}

Congratulations, you just changed the title. 

…cue the sound of a thousand keyboards furiously hacking.

One thought on “WordPress REST API Quickstart”

Leave a Reply

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