Getting Started with the WP REST API
Posted in WordPress on the 21st of November 2016 by @aaronrutley
Posted in WordPress on the 21st of November 2016 by @aaronrutley
Last week at the Melbourne WordPress Developer Meetup I gave a presentation on ‘Getting Started with the WordPress REST API’ here’s a follow-up post about it.
The purpose of this post is to introduce the WP REST API and to explain some practical ways developers can get started using it in their projects!
For anyone that’s not familiar with the WordPress REST API, it’s essentially an alternative way for developers to communicate with the WordPress database.
It’s been under development for the past few years, Ryan, Rachel & the team have put in a huge amount of work. It’s exciting to see the content endpoints will be in WordPress version 4.7 due for release in early December 2016.
TLDR; It’s a developer friendly, well-structured way to talk to the WP database.
The endpoint to GET the latest posts from my blog is:
http://aaronrutley.com/wp-json/wp/v2/posts
If you wanted to GET page 2 of my blog you could hit this endpoint:
http://aaronrutley.com/wp-json/wp/v2/posts?per_page=10&page=2
The endpoint to GET the details the details of post 3556 would be
http://aaronrutley.com/wp-json/wp/v2/posts/3556
You can explore all endpoints / routes / resources here:
http://aaronrutley.com/wp-json/wp/v2
Please note – I’m using a bespoke page builder so not all of my content is displayed right now.
The endpoint to POST a new page would be:
http://aaronrutley.com/wp-json/wp/v2/pages
The endpoint to PUT data to update a page with an id of 4 would be:
http://aaronrutley.com/wp-json/wp/v2/pages/4
Please note – this would require authentication which is covered in the WP REST API docs.
In WordPress 4.7 we’ll have endpoints for the following
You can read more about the content endpoints over on the make.wordpress.org blog.
By default, Custom Post Types are not exposed in the REST API. However, you can easily change that by defining 'show_in_rest' => true,
wherever you registered your custom post type.
Here’s an example of a custom post type endpoint on a site I created recently called AwesomeACF:
http://awesomeacf.com/wp-json/wp/v2/extension
Here’s an example of a CPT endpoint that queries just the latest 10 extensions:
http://awesomeacf.com/wp-json/wp/v2/extension?orderby=date&order=desc&per_page=10
It’s possible to include custom meta data in the API response for any post type, this is ideal for exposing select data you might have registered with Advanced Custom Fields, you can use this gist to get you started.
It’s also possible to create your own endpoints, for the AwesomeACF site I wanted an endpoint that listed all 100+ items & no other data, here’s the gist and here’s the endpoint:
http://awesomeacf.com/wp-json/wp/v2/extensions