WordPress REST API
An ExplorationRoy Emory
Using WordPress
(Without WordPress)“The REST API allows grabing the same data you
normally would, but put it into a box.. then use ANYTHING* to grab the data from the box”.
Create/edit content/datastore
View/edit content
*angular.js, .net, node.js, html/php(Laraval), backbone.js, ember.js, native mobile code, react.js, c++, etc.
Definitions• WordPress = a website creation & management tool written in PHP
– Front end display based on PHP-based template system. The REST API allows alternate technologies for front end display while still using the WordPressmanagement tools.
• REST = Representational State Transfer – a software architecture style, not a standard– RESTful systems typically, communicate over the Hypertext Transfer Protocol
with the same HTTP verbs (POST, GET, PUT, DELETE, etc.) which web browsers use to retrieve web pages and to send data to remote servers
– Servers are not concerned with the user interface or user state; clients are not concerned with data storage
– part of RESTful API description is the specification of returned data structures. The WordPress REST API specifies the JSON Schema data description format.
• API = Application Programming Interface –allows product or service to talk to other products or services.
3
JSON
• JSON = JavaScript Object Notation– intended solely as a data serialization format– its design as a non-strict subset of the JavaScript
scripting language poses several security concerns• Example JSON data (5 elements [red, green,
orange, blue, red] in the array each with in a “tag”: value notation)["id": 1, "name": "Foo", "price": 123, "taglist": [
"Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } ]
4
Basic http web communication
• Client – Your computer’s (smart
phone, etc) browser– Talks back and forth with
Server using HTTP communication protocol
• Server – The remote computer
typically executing PHP code
5
What is it? Why use it?
• The advent of the WP REST API is the most explosive update to happen to agile software development for the web and mobile this decade. It is a project that will instantly scale over 24% of the entire Internet this 2015 or 2016. [1]
• Separating the UX layer of a site allows developers to leverage the tools they want, making the frontend truly agile and the end-user experience more friendly. [2]
6
Pros & Cons
• Pro– The experience of pre-loading all the content allows users to zip around
without any delay. It’s a dramatic improvement. – Front end development can use any available technology– Permits future offline app functionality (receive data, disconnect, reconnect,
update data)– Scales well as server load is reduced (less php server work) + CDN all template
files, easy to cache js and html files, use AJAX for UI/UX.– Potential new backend dashboard(s)– Provides a way to retrieve pure data (usually in JSON format) over HTTP – No loops necessary– Good for mobile apps and environments where you don’t want a full webpage
to render but want content from a blog or site– With the official directory now welcoming these types of themes, it won’t be
long before the entire landscape of WordPress theme development changes. The team has unanimously agreed to allow themes to require the REST API plugin as a temporary measure until it is available in core (4.4?)
7
Pros & Cons• Con
– Entire site data downloaded upfront could delay time to display screen to user
– User authorization to change content is not straight forward– Better accessibility when we render the page with server-side
scripts like PHP and only load (change) content with JavaScript when the user interacts with the page
– A large variation in javascript parse and execution times across devices and browsers (especially mobile)
– Serialized meta data is not allowed to be read or stored using the WP API *
– protected meta cannot be accessed or saved via the WP API **
8
REST API PLUGIN v1(a)
• https://wordpress.org/plugins/json-rest-api/– VERSION 1.2.3 14Aug2015
– This plugin provides an easy to use REST API– Grab your site's data in simple JSON format, including
users, posts, taxonomies and more. – Retrieving or updating data by sending a HTTP request– WP REST API exposes a simple yet easy interface to
WP Query, the posts API, post meta API, users API, revisions API and many more.
9
REST API PLUGIN v1(b)
– Documentation for information on what's available in the API and how to use it. http://wp-api.org/• Additional documentation exists on extending the
API with adding additional fields to resources and adding endpoints to the API– probably with an additional plugin
• [Getting Started]: http://wp-api.org/guides/getting-started.html[guides]: http://wp-api.org/guides.html[post-routes]: http://wp-api.org/#posts[media-routes]: http://wp-api.org/#media
10
REST API PLUGIN v2
• https://wordpress.org/plugins/rest-api/– Version 2 Beta 4 (WordPress 4.3+ only)
14Aug2015 non-backwards-compatible edition of the API intended specifically for core integration
– exposes 9 objects: Posts, Pages, Media, Post meta, Post revisions, Comments, Taxonomies, Terms, Users
– (Have not tested this version yet.)
11
My Initial Setup• localhost multisite –site with example content
– New theme barebones • index.php (just a html5 minimal shell)• style.css (w/theme comment “Angular REST” on top)• Save files, activate theme “Angular REST”• Add WP Example Content plugin as test
– Plugin https://wordpress.org/plugins/json-rest-api• Stable Version: 1.2.3• Or dev version 2.0
– https://wordpress.org/plugins/rest-api/ (beta3)– https://github.com/WP-API/WP-API (nightly builds - bleeding edge)
• Once this is installed, you can get posts in JSON format with /wp-json/posts and pages with /wp-json/pages; also JSON site info with /wp-json/
12
Basic WP site demo 1
Basic WP using Angular demo 2
Access Site via non-WordPress
• Install– angular.js via CDN v1.4.2 dated 6 July 2015
https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js
– route-angular.js also needed• https://code.angularjs.org/1.4.2/ -> angular-route.js
• Change theme
13
Angular only demo v1 data binding demo 3
Angular only demo: data binding
14
THEME:\wp-content\themes\angular-wp-rest-api-1
FILE NAME bytes1. style.css 217 2. index.php 824 /js3. scripts.js 352 /partials4. main.html 21
Angular only demo: data binding
15
THEME:\wp-content\themes\angular-wp-rest-api-1
FILE NAME bytes1. style.css 217
/*Theme Name: Angular REST v1Author: Roy EmoryDescription: This theme is a starting point using angular.js and wp-rest-api. */
/*verification that style sheet is being loaded*/h1 a{
color: blue;}
16
THEME: \wp-content\themes\angular-wp-rest-api-1FILE NAME bytes2. index.php 824
<!DOCTYPE html><html ng-app="app"><head>
<base href="/test1/"><title>WP REST API test via angularjs</title><link rel="stylesheet" type="text/css" href="wp-content/themes/angular-wp-rest-api-1/style.css"><script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script><script src="https://code.angularjs.org/1.4.2/angular-route.js"></script><script src="wp-content/themes/angular-wp-rest-api-1/js/scripts.js"></script>
</head><body><header>
<h1><a href="<?php echo site_url(); ?>">Angular JS Demo Theme version 1</a</h1></header><div ng-view></div><div><input type="text" ng-model="name“>
<p>Hello, {{name}}!</p></div><footer>© <?php echo date( 'Y' );?> </footer></body></html>
Angular only demo: data binding
Angular only demo: data binding
17
THEME:\wp-content\themes\angular-wp-rest-api-1FILE NAME bytes3. /js/scripts.js 352
angular.module('app', ['ngRoute']).config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);$routeProvider.when('/', {
templateUrl: '/test1/wp-content/themes/angular-wp-rest-api-1/partials/main.html',controller: 'Main'
});}).controller('Main', function() {
console.log('Main file loaded.');});
Angular only demo: data binding
18
THEME:\wp-content\themes\angular-wp-rest-api-1
FILE NAME bytes4. /partials/main.html 21
This is the main file
Access Site via non-WordPress
• Develop new Front end – Change Theme to another javascript app– angular-sanitize.js also needed
19
Angular demo v2: Post titles & Single Posts
Angular demoPost titles & Single Posts
20
THEME:\wp-content\themes\angular-wp-rest-api-2
FILE NAME bytes1. style.css 340 2. index.php 892 /js3. scripts.js 742 /partials4. main.html 1055. content.html 64
Angular demoPost titles & Single Posts
21
THEME:\wp-content\themes\angular-wp-rest-api-2
FILE NAME bytes1. style.css 340
/*Theme Name: Angular REST v2Author: Roy EmoryDescription: This theme is a starting point using angular.js and wp-rest-api. */
/*verification that style sheet is being loaded*/body {
margin: 50px 100px;}h1 a{
color: green;}
22
THEME: \wp-content\themes\angular-wp-rest-api-2FILE NAME bytes2. index.php 892
<!DOCTYPE html><html ng-app="app"><head>
<base href="/test1/"><title>WP REST API test via angularjs</title><link rel="stylesheet" type="text/css" href="wp-content/themes/angular-wp-rest-api-2/style.css"><script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script><script src="https://code.angularjs.org/1.4.2/angular-route.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular-sanitize.js"></script><script src="wp-content/themes/angular-wp-rest-api-2/js/scripts.js"></script>
</head><body><header>
<h1><a href="<?php echo site_url(); ?>">Angular JS Demo Theme version 2</a</h1></header><div ng-view></div><div><input type="text" ng-model="name“>
<p>Hello, {{name}}!</p></div><footer>© <?php echo date( 'Y' ); //This is the only php used.?> </footer></body></html>
Angular demo: Post titles & Single Posts
23
Angular demo: Post titles & Single PostsFILE NAME bytes3. /js/scripts.js 742
angular.module('app', ['ngRoute', 'ngSanitize']).config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);$routeProvider.when('/', {
templateUrl: '/test1/wp-content/themes/angular-wp-rest-api-2/partials/main.html',controller: 'Main‘
}).when('/:ID', {
templateUrl: '/test1/wp-content/themes/angular-wp-rest-api-2/partials/content.html',controller: 'Content‘
});}).controller('Main', function($scope, $http, $routeParams) {
$http.get('wp-json/posts/').success(function(res){$scope.posts = res;
});}).controller('Content', function($scope, $http, $routeParams) {
$http.get('wp-json/posts/' + $routeParams.ID).success(function(res){$scope.post = res;
});});
Angular demoPost titles & Single Posts
24
THEME:\wp-content\themes\angular-wp-rest-api-2
FILE NAME bytes4. /partials/main.html 105
<ul><li ng-repeat="post in posts">
<a href="{{post.ID}}">{{post.title}}
</a></li>
</ul>
Angular demoPost titles & Single Posts
25
THEME:\wp-content\themes\angular-wp-rest-api-2
FILE NAME bytes5. /partials/content.html 64
<h1>{{post.title}}</h1><div ng-bind-html="post.content"></div>
Allow app users access to backend• Install OAuth plugin (exercise left to the reader)
– Place code in wp-content/plugins/oauth-server – Code available at https://github.com/WP-API/OAuth1– Activate to generate a key/secret that can be used for OAuth
authentication. – http://www.sitepoint.com/wp-api-and-oauth-using-wordpress-
without-wordpress/• Note: OAuth 1.0 was officially deprecated on April 20, 2012 according
to Google • OAuth2 premium plugin exists but does not work with WP-API yet
(nor with multisite). Furthermore, it shouldn’t be used on shared servers. Also requires https protocol.
• Alternate: use cookies or HTTP basic authentication (every request)
26
Theme file structureStandard PHP vs React.js (dev)
theme-name/content-page.phpcontent-single.phpcontent.phpindex.phpsingle.phppage.phpfunctions.phpheader.phpfooter.phpstyle.cssjs.js
theme-name/index.phpstyle.csstheme-name.jscomponents/
content/content.jsxloop/
loop.jsxhentry/
hentry.jsxrouter/
router.jsxtheme-name.jsx
27
Other ways of using REST API
• First page load via say WordPress, then javascript for remaining content/navigation of site.
• Only some portions of site would use SPA approach
28
Example REST API uses• WP.com got a REST API in 2012. Google funded the REST API in the SOC-2013 with Ryan McCue• Human Made uses the API with client projects, i.e. to create a Node-powered frontend and
maintain the familiar WordPress admin.• Reactor uses the API to create mobile apps that digest the API themselves.• Aesop Interactive uses the API with Lasso and also to power the WP Live Search plugin.• A large industrial real estate firm manages its properties via an internal proprietary .NET app with a
public-facing site powered by WP. It uses the API to sync property data (in real time) between the internal app and the website so the real estate listings will always be current.
• Join In, a site organizing volunteers in the UK, used the API to create an embeddable JS widget.• Per Soderlind used the WP REST API as a backend for an iOS application for the Norwegian Ministry
of Petroleum and Energy.• Modern Tribe is building sites that use the REST API to power both Handlebars and full page React
templates in themes.• Rachael Baker “A good example is Wired Magazine. Wired recently replaced multiple WordPress
installs with one install, linked to multiple front-ends via the REST API. …the REST API will allow developers to choose their own way of working with WordPress. No longer will developers have to use a theme in the traditional way. They can use the JSON data any way they want.”
• New York Times Live Blogs: Front end served by WordPress for SEO, but data is rendered by web-socket via React.
29
References – part 11. http://jacklenox.com/2015/03/30/building-themes-with-the-wp-rest-api-wordcamp-london-
march-2015/2. https://speakerdeck.com/jacklenox/theming-react-and-the-rest-api/ 'wordcamp europe
2015‘3. https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/ “Yoren Chang’s article was
used as reference for this slide show. Subsequent articles: https://1fix.io/angularjs-wp-rest-api/ I used the next article 2014/11/13 - ngBindHtml to finish display of the post and a link to angular-sanitize.js CDN.
4. https://make.wordpress.org/core/2015/05/18/wp-rest-api-version-1-2-2/4 ‘Rachel Baker and Ryan McCue ’
5. https://poststatus.com/a-future-api/6. https://css-tricks.com/using-the-wp-api-to-fetch-posts/7. http://premium.wpmudev.org/blog/wordpress-rest-api/8. http://adrianmejia.com/blog/2012/09/11/backbone-dot-js-for-absolute-beginners-getting-
started/
30
References – part 29. https://wordpress.tv/2014/11/03/k-adam-white-wordpress-in-weird-places-content-
management-for-node-using-rest/ ...Slides: http://kadamwhite.github.io/talks/2014/wcsf-node-wp
10. http://wptavern.com/new-wp-live-search-plugin-utilizes-the-wp-rest-api11. http://torquemag.io/processing-forms-ajax-using-json-rest-api/12. https://make.wordpress.org/core/2015/07/23/rest-api-whos-using-this-thing/13. https://poststatus.com/a-future-api/14. https://wordpress.org/plugins/oauth2-provider/ ‘WP OAuth Server plugin (3.1.3) supports
authentication for the WP REST API‘15. http://www.sitepoint.com/wp-api-and-oauth-using-wordpress-without-wordpress/16. http://wptavern.com/new-feature-plugin-proposed-oembed-for-wordpress-posts 'requires
v2 rest api & wp v4.3+’17. http://torquemag.io/adding-custom-routes-wordpress-rest-api/
31
References – part 318. https://gist.github.com/petenelson/6dc1a405a6e7627b4834 ‘return of non-JSON results
from WP-API'19. http://studioraygun.co.uk/blog/web-development/angularjs-front-end-wordpress-back-end/20. http://observer.com/2015/07/wordpress-rest-api/21. https://github.com/WP-API/WP-API/releases/tag/2.0-beta3 / July 1, 201522. http://wptavern.com/explore-the-wordpress-rest-api-with-the-new-interactive-console-
plugin23. https://github.com/WP-API/rest-api-console GitHub link to the rest API console 24. https://deliciousbrains.com/creating-mobile-app-wp-api-react-native/25. session on using REST API for Sept 2015 Wordcamp .Pune – should be on WordCamp.tv later26. http://www.slideshare.net/tlovett1/the-json-rest-api-for-wordpress27. http://www.roysivan.com/launching-angularjs-client-side-application-powered-wordpress/28. http://wptavern.com/decoupling-wordpress/29. http://www.slideshare.net/ScottTaylor1/2015-wordcamp-maine-keynote ‘some REST API
gotchas’30. http://laralittlefield.pub/24-percent-internet-scale-wp-api/#.VZ8XYMvJCM831. https://github.com/Mashape/mashape-oauth/blob/master/FLOWS.md#oauth-10a-three-
legged 32
33
And now some real demos
• CodeCalvary.com– WordPress
• Users• Users Authentication• Custom Post Types• Data Storage
– S.P.A• Session Create• Firebase – WebSocket• User Dashboard• User Profiles
34
Reference: JSON's 6 basic types
• Number: a signed decimal number that may contain a fractional part and may use exponential E notation. JSON does not allow non-numbers like NaN, nor does it make any distinction between integer and floating-point. (Even though JavaScript uses a double-precision floating-point format for all its numeric values, other languages implementing JSON may encode numbers differently)
• String: a sequence of zero or more Unicode characters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.
• Boolean: either of the values true or false• Array: an ordered list of zero or more values, each of which may be of any type.
Arrays use square bracket notation with elements being comma-separated.• Object: an unordered collection of name/value pairs where the names (also called
keys) are strings. Since objects are intended to represent associative arrays,[10] it is recommended, though not required,[11] that each key is unique within an object. Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.
• null: An empty value, using the word null
35
Already in coreas of WP2.7
• WP HTTP requests– https://codex.wordpress.org/HTTP_API
• many possible ways to send an HTTP request• The purpose for the HTTP API is to support as many of these
requests as possible with an API that is simple and standard for each of the request types (GET, POST, HEAD, PUT, DELETE …)
• https://johnblackbourn.com/wordpress-http-api-basicauth• http://www.sitepoint.com/the-wordpress-http-api/• And for more basic understanding of http protocol:
http://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039
– header, body, response support, compression, cookie support and proxy support provided as of WP2.8
36
How the WordPress HTTP API works
• Four methods used to make requests and intercept the responses are:– wp_remote_get()– wp_remote_post()– wp_remote_head()– wp_remote_request()
• Five additional functions– wp_remote_retrieve_body()– wp_remote_retrieve_header()– wp_remote_retrieve_headers()– wp_remote_retrieve_response_code()– wp_remote_retrieve_response_message()
• Reference: https://kinsta.com/blog/using-http-api-wordpress/
37