wordpress rest api - what, how and why?
TRANSCRIPT
WordPress REST APIWhat, How & Why
Nikhil Vishnu@nikhilvishnu
Who am I?
I’m Nikhil Vishnu
● Co-founder and CEO of Mobapper● Working with WordPress for 7 years● Mobile App Developer● WordCamp speaker
What is WordPress JSON REST API?
JSONJavascript Object Notation
{"name" : "Nikhil Vishnu",
"company" : "Mobapper",
"hometown" : "Kottayam, Kerala",
"gender" : "male"
};
REST Representational State Transfer
POST
GET
PUT
DELETE
Create
Read
Update
Delete
APIApplication Programming Interface
"User Interface" that software uses to interact with other software.
YouTube
WordPress JSON REST API
“Easy to use REST APIs for retrieving or updating your WordPress website data in simple JSON format.”
WordPress REST API
www.wp-api.org
Why do we need it?
WordPress External API
● XML RPC is very complicated
● 40% of WordPress iOS App code is just for cleaning up xml
How to use WordPress REST API?
Install Pluginhttps://wordpress.org/plugins/rest-api/
What is Available?● wp-json
○ Show all the routes and end points● wp-json/posts
○ create, read, update and delete posts● wp-json/users
○ create,read,update, delete users● wp-json/media
○ create,read,update and delete media items● wp-json/taxonomies
○ read taxonomies and terms● wp-json/pages
○ create,read and delete pages● ...
List all Endpoints
GET /wp-json
List Posts
GET /wp-json/posts
List Posts Parameters
● Filter[] : Accepts WP_Query arguments
● Page : Allows for pagination
● Context : Usage context ‘View’ or ‘Edit’
GET /posts?filter[posts_per_page]=8&filter[order]=ASC
GET /posts?page=1
Retrieve A Post
POST /wp-json/posts/<id>POSTGET
Edit A Post
POST /wp-json/posts/<id>POSTGETPUT
Create A Post
POST /wp-json/posts/POSTGETPOST
Taxonomies
POST /wp-json/taxonomies/POSTGETPOSTGET
Taxonomy Terms
POST /wp-json/terms/categoryPOSTGETPOSTGET
API Documentation
http://wp-api.org
Authentication
● Cookie Authentication (client side)○ For themes & Plugins○ Using nonces for CSRF attacks
● OAuth 1.0○ For external apps○ WP Auth plugin
● HTTP Basic Auth○ For development○ WP Basic Auth Plugin
Custom Endpoints<?php
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
Registering Route<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
Where we can use WP API?
Where we can use it?
● Display and manage content in mobile app
● Custom dashboard
● Backbone.js themes/plugins
● Form validation
● Integrate content with other platforms
● Integrate other platforms with WordPress
● ...
Questions?@nikhilvishnu