REST API

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 in YARC
7 Options in YARC

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

Multisite

Pressbooks has different API endpoints for book and the root site:

Book vs. Root
Book vs. Root

Features

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

_links
_links
To reduce the number of HTTP requests use the *embed parameter to tell the API that the response should include embeddable resources.
_embedded
10 _embedded
WP API exposes pagination info in the response header.
Pagination
11 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>This is the first chapter in the main body of the text. You can change the text, rename the chapter, add new chapters, and add new parts.</p>",
    "protected": false
  }
}

Pressbooks makes use of WordPress’ REST API, which does not verify the Origin header of incoming requests, meaning that public REST API endpoints may therefore be accessed from any site. According to WordPress, this is an intentional design decision, as the project has an existing CSRF protection mechanism which uses nonces. If you wish to prevent your site from being accessed from unknown origins, you can consult the WordPress REST API FAQ or implement something like this plugin which implements a stricter CORS policy.

Edit this post on GitHub.