INTRO to the WordPress REST API
Seattle WordPress Dev Meetup
February 2016
thank you wework
INTRO TO THE REST API
one. welcome!
First WordPress Dev Meetup of 2016
- Goals
- Contributing
one. welcome!
This is our meetup...
INTRO TO THE REST API
ONE. WELCOME!
Upcoming WordPress events
one. welcome!
INTRO TO THE REST API
ONE. WELCOME!
18 February | Contributor Meetup (Greenwood) |
23 February | Eastside WordPress Meetup |
5 March | Contributor Meetup (SLU) |
15 March | The Big Meetup is back! |
22 March | WP Developers: From Code to Client |
wpseattleslack.wordpress.com
INTRO TO THE REST API
ONE. WELCOME!
slack channel
Also, always learning!
INTRO TO THE REST API
ONE. WELCOME!
WHO am I?
Darren Krape
- Program manager at Amazon by day... WordPress freelancer, experimenter by night
- Run WordPress Dev Meetup
darrenkrape.com | twitter.com/dkrape |
INTRO TO THE REST API
ONE. WELCOME!
what i'll cover
- Welcome!
- What is the REST API?
- What's in it for me?
- Trying it out
- The REST API on your site
- In practice
- Resources
Two. What is the rest api?
INTRO TO THE REST API
TWO. What is the rest api?
API
Web browser
INTRO TO THE REST API
two. what is the rest api?
What is an api?
Application Programming Interface
What is REST?
REpresentational State Transfer
INTRO TO THE REST API
two. what is the rest api?
INTRO TO THE REST API
two. what is the rest api?
Um. What?
1. Access through resource types
JSON, HTML, etc.
2. Communicate through representations
api.example.com/post/3
api.example.com/user/7
api.example.com/todo/3/item/18
INTRO TO THE REST API
two. what is the rest api?
basically: rest is an architecture for managing information
GET | Gets a resource |
POST | Creates a resource |
PUT | Updates a resource |
DELETE | Deletes a resource |
INTRO TO THE REST API
two. what is the rest api?
act through http verbs
INTRO TO THE REST API
two. what is the rest api?
act through http verbs
GET /wp/v2/posts/3 | Gets post 3 |
PUT /wp/v2/posts/3 | Updates post 3 |
DELETE /wp/v2/post/3 | Deletes (trashes) post 3 |
wired.com/wp-json
wired.com/wp-json/wp/v2/posts/1974761
darrenkrape.com/wp-json/wp/v2/comments/197508
INTRO TO THE REST API
two. what is the rest api?
try it now
{"id":197508,"post":957,"parent":0,"author":0,"author_name":"Whitney Krape","author_url":"http:\/\/www.whitneykrape.com\/","author_avatar_urls":{"24":"http:\/\/0.gravatar.com\/avatar\/06bd4d92401c74fba79aad89980b5efe?s=24&d=mm&r=g","48":"http:\/\/0.gravatar.com\/avatar\/06bd4d92401c74fba79aad89980b5efe?s=48&d=mm&r=g","96":"http:\/\/0.gravatar.com\/avatar\/06bd4d92401c74fba79aad89980b5efe?s=96&d=mm&r=g"},"date":"2015-06-04T15:56:00","date_gmt":"2015-06-04T20:56:00","content":{"rendered":"<p>Great post, very thorough and some solid tips that often get overlooked. The backpack comment “a jury-rigged day-pack” really stood out, shouldering that all day is serious pain. For my part a 60-65? liter was overkill in Japan, which was really glorified day trekking, but having the weight well distributed made a huge difference.<\/p>\n"},"link":"http:\/\/www.darrenkrape.com\/first-time-backpacker\/comment-page-1\/#comment-197508","status":"approved","type":"comment","_links":{"self":[{"href":"http:\/\/www.darrenkrape.com\/wp-json\/wp\/v2\/comments\/197508"}],"collection":[{"href":"http:\/\/www.darrenkrape.com\/wp-json\/wp\/v2\/comments"}],"up":[{"embeddable":true,"post_type":"post","href":"http:\/\/www.darrenkrape.com\/wp-json\/wp\/v2\/posts\/957"}]}}
INTRO TO THE REST API
two. what is the rest api?
...what do you get?
INTRO TO THE REST API
two. what is the rest api?
JSON!
var sasha = {
"age" : "6",
"species" : "cat",
"hometown" : "Seattle, WA",
"gender" : "female"
};
JSON
JavaScript Object Notation
Basically, JSON is a method to store information in an organized, easy-to-access manner
INTRO TO THE REST API
two. what is the rest api?
Text
INTRO TO THE REST API
two. what is the rest api?
{
"id": 197508,
"post": 957,
"parent": 0,
"author": 0,
"author_name": "Whitney Krape",
"author_url": "http://www.whitneykrape.com/",
"author_avatar_urls": {
"24": "http://0.gravatar.com/avatar/06bd4d92401c74fba79aad89980b5efe?s=24&d=mm&r=g",
"48": "http://0.gravatar.com/avatar/06bd4d92401c74fba79aad89980b5efe?s=48&d=mm&r=g",
"96": "http://0.gravatar.com/avatar/06bd4d92401c74fba79aad89980b5efe?s=96&d=mm&r=g"
},
"date": "2015-06-04T15:56:00",
"date_gmt": "2015-06-04T20:56:00",
"content": {
"rendered": "<p>Great post, very thorough and some solid tips that often get overlooked. The backpack comment “a jury-rigged day-pack” really stood out, shouldering that all day is serious pain. For my part a 60-65? liter was overkill in Japan, which was really glorified day trekking, but having the weight well distributed made a huge difference.</p>\n"
},
"link": "http://www.darrenkrape.com/first-time-backpacker/comment-page-1/#comment-197508",
"status": "approved",
"type": "comment",
"_links": {
"self": [
{
"href": "http://www.darrenkrape.com/wp-json/wp/v2/comments/197508"
}
],
"collection": [
{
"href": "http://www.darrenkrape.com/wp-json/wp/v2/comments"
}
],
"up": [
{
"embeddable": true,
"post_type": "post",
"href": "http://www.darrenkrape.com/wp-json/wp/v2/posts/957"
}
]
}
}
INTRO TO THE REST API
two. what is the rest api?
INTRO TO THE REST API
three. what's in it for me?
three. what's in it for me?
INTRO TO THE REST API
three. what's in it for me?
example use-cases
- AJAX, without admin-ajax.php (Yay!)
- Integrate across platforms (such as a mobile app)
- Replace front-end, without using PHP
- Pull content from another WordPress site
INTRO TO THE REST API
three. what's in it for me?
Downsides
- Many WordPress benefits are frontend
- JavaScript knowledge starts becoming a requirement
- Not many plugins support it
- Documentation is limited, and occasionally outdated
- In the (very) early days
INTRO TO THE REST API
three. what's in it for me?
Where are we now?
- REST API infrastructure added in 4.4
- Endpoints are a plugin, integration is coming... sometime (just dropped from 4.5)
- Plugin is beta, some updates are breaking changes
- Post meta is still up in the air (recently added as a separate plugin)
INTRO TO THE REST API
FOUR. TRYING IT OUT
FOUR. Let's give it a spin
$(document).ready( function() {
$.ajax({
url: 'http://www.wired.com/wp-json/wp/v2/posts/',
type: "GET",
}).success( function( response ){
$.each( response, function( key, post ) {
$('#posts').append('<h3><a href="'+post.link+'">'+post.title.rendered+'</a></h3>');
});
});
});
INTRO TO THE REST API
FOUR. TRYING IT OUT
USE AJAX TO GET POST TITLES
INTRO TO THE REST API
FOUR. TRYING IT OUT
USE AJAX TO GET POST TITLES
/posts |
/pages |
/media |
/types Posts, pages, attachments, CPT ... |
/statuses Published, ... |
wired.com/wp-json/wp/v2/posts
INTRO TO THE REST API
FOUR. TRYING IT OUT
end points
/comments |
/taxonomies Categories, tags, custom taxonomies |
/categories |
/tags |
/users |
Arguments | Parameters |
author | [id] |
order | asc, desc |
orderby | date, id, include, title, slug |
per_page | [num] |
search | [text] |
wired.com/wp-json/wp/v2/posts/?per_page=1
&order=desc&orderby=title
INTRO TO THE REST API
FOUR. TRYING IT OUT
FILTERING REQUESTS
/posts/?filter[posts_per_page]=1
/posts/?filter[orderby]=title&filter[order]=asc
INTRO TO THE REST API
FOUR. TRYING IT OUT
FILTERING REQUESTS
You can also use WP_Query arguments
INTRO TO THE REST API
FIVE. THE REST API ON YOUR SITE
FIVE. THE REST API ON YOUR SITE
INTRO TO THE REST API
Five. the rest api on your site
setting it up
Get the plugin
add_action( 'init', 'my_book_cpt' );
function my_book_cpt() {
$args = array(
// Frontend
'has_archive' => false,
'public' => true,
// Admin
'capability_type' => 'post',
'supports' => array( 'editor', 'title' ),
// Rest
'show_in_rest' => true,
'rest_base' => 'books',
);
register_post_type( 'book', $args );
}
INTRO TO THE REST API
Five. the rest api on your site
ADDING CUSTOM POST TYPE ENDPOINT
darrenkrape.com/wp-json/v2/wp/books
INTRO TO THE REST API
Five. the rest api on your site
ADDING custom post type ENDPOINT
function get_author_recent_post( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
Custom endpoint callback
INTRO TO THE REST API
Five. the rest api on your site
adding custom endpoint
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'get_author_recent_post',
) );
} );
Registering route
INTRO TO THE REST API
Five. the rest api on your site
adding custom endpoint
INTRO TO THE REST API
Five. the rest api on your site
adding custom endpoint
darrenkrape.com/wp-json/v2/wp/author/1
INTRO TO THE REST API
Five. the rest api on your site
POST META
Meta is in flux. See more on GitHub #1425 and Ryan McCue (lead dev)
// Unprotect ISBN field callback
public function unprotect_answers_field( $protected, $meta_key ) {
if( '_isbn' == $meta_key || '_isbn' == $meta_key && defined( 'REST_REQUEST' ) && REST_REQUEST ) {
$protected = false;
}
return $protected;
}
// Unprotect ISBN field
add_filter( 'is_protected_meta', 'unprotect_isbn_field' );
INTRO TO THE REST API
Five. the rest api on your site
POST META
// Registering ISBN field
public function register_isbn_field() {
register_rest_field( 'question',
'_isbn',
array(
'get_callback' => array( $this, 'get_isbn_cb' ),
'update_callback' => null,
'schema' => null
)
);
}
// Callback to get ISBN field
public function get_isbn_cb( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name );
}
// Action for registering field
add_action( 'rest_api_init', array( $this, 'register_isbn_field' ) );
$(document).ready( function() {
$.ajax({
url: 'http://www.wired.com/wp-json/wp/v2/posts/?_jsonp=?',
type: "GET",
dataType: 'jsonp',
}).success( function( response ){
$.each( response, function( key, post ) {
$('#posts').append('<h3><a href="'+post.link+'">'+post.title.rendered+'</a></h3>');
});
});
});
INTRO TO THE REST API
Five. the rest api on your site
ACCESSING ACROSS DOMAINS: JSONP
add_action( 'rest_api_init', function() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $value ) {
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Methods: GET' );
return $value;
});
}, 15 );
Reference: Josh Pollack (above code)
INTRO TO THE REST API
Five. the rest api on your site
ACCESSING ACROSS DOMAINS: CORS
Cookie (client side)
- Themes and plugins
- Uses nonces for CSRF protection
INTRO TO THE REST API
Five. the rest api on your site
Authentication
INTRO TO THE REST API
Six. in practice
Six. in practice: wp-quiz.com
INTRO TO THE REST API
six. in practice
INTRO TO THE REST API
SIX. IN PRACTICE
wp-quiz.com
- Custom routes
- Custom post types
- Cookie-based authentication
- Protected meta
- Templating with underscores.js
INTRO TO THE REST API
seven. Resources
seven. resources
INTRO TO THE REST API
Seven. resources
resources
WordPress REST API
By Darren Krape
WordPress REST API
- 2,902