WordPress REST API provides a uniform interface for interacting with the data in a WordPress site.
In this lesson, you'll learn how to use the REST API to fetch data from your WordPress site.
You'll discover three internal options for making REST API requests,
and then use them to perform a GET request to fetch some public custom post type data.
If you completed the introduction to WordPress plugins module,
you bought a plugin that registers a custom post type called Book.
If you skip that module, you can download the main plugin code
from the GitHub repository by clicking on the Bookstore plugin link.
Once you have the plugin installed and activated, open the main plugin file in your code editor.
You will notice that one of the arguments passed the register post type function is
ShowInRest. This argument is set to true, which means that the custom post type is available
to the REST API. This also means that if you browse to the REST API's book root,
you will see the custom post type data in the response. If you take a look at the register
post type function reference, you'll see a few additional arguments that can be used to control
the REST API response. For example, you can change the REST-based argument to change the
root that the custom post type data is available that. Given that you would expect to be able to
fetch more than one book from the book root, it would be a good idea to change the REST-based
to books. So we can say REST-based.
Doing this will allow you to make requests to the box root to access books via the REST API.
Let's say you want to add a page in your WordPress dashboard that fetches the box
and displays a list of book titles and permalinks in a comma-separated list.
To start, you might add an admin submenu page to the books menu using the admin menu hook
and the add submenu page function. Then you could create the bookstore render booklist
callback function, which would output the HTML for the admin page. Now if you browse the dashboard
and click on the books menu, you will see the new submenu page called booklist.
Clicking on that link will take you to the page with a load box button and a text area.
Now you could add functionality to the bookstore render booklist function, which fetches the booklist
via PHP and make the button trigger a page refresh. However, for a smoother user experience,
you'd like to use some JavaScript and the REST API to fetch the book data asynchronously
and populate the booklist without having to wait for a full page refresh.
In the introduction to WordPress plugins module, you learned how to include JavaScript file in your
plugin. Because this functionality is being added to the admin dashboard, you need to set up a
separate WP-InQScript function call hooked into the admin-inq-scripts hook so that the JavaScript
file is only loaded in the admin dashboard. First, create a new JavaScript file in the
plugin directory to handle the admin JavaScript. We'll call this one admin-bookstore.js.
Then add the following code to the main plugin file to enqueue the JavaScript file for the
dashboard. We'll start with add action admin-in-q-scripts and we'll define
a callback function. Then we'll create the function
and then use WP-InQScript to enqueue the script file.
(
)
Notice that this code not only enqueues the JavaScript file, but also specifies an empty
dependencies array, a version number, and that it should be enqueued in the footer of
the HTML page by setting that last argument to true.
You can read more about these parameters in the WPEnqueueScript function reference under
the parameters section.
You could now test that it's enqueued correctly by adding a single alert to the admin bookstore
JS file, and then refreshing any admin dashboard page.
Once you're sure it's working, remove that line from the file.
Since the REST API was added to WordPress, it has included a Backbone.js REST API JavaScript
client for making direct requests to the WordPress REST API.
This client provides an interface for using the REST API by providing models and collections
for all endpoints exposed through the API.
To ensure that your JavaScript code is able to use this REST API client, you need to add
it as a dependency to your enqueue JavaScript.
The third argument for WPEnqueueScript is an array of dependencies, and you can add
WPAPI as a dependency to your enqueueScript function call to enable the REST API client.
This will ensure that your plugin's JavaScript is only loaded after the REST API JavaScript
client is loaded, and so that you can use it in your plugin.
You'll want to start by registering a click event handler for the button.
Let's find the button ID, and it's bookstore load box.
Then in our JavaScript, we can say, "Loadbooks irrest button is document getElementByID"
and pass in the bookstore load box.
Let me just say, "if the button does exist," then we will add the event listener to the
button, and we will listen for any click events.
If the click event is fired, this is the callback function for that event, and then inside here
we can do something.
Then, inside the event handler function, you can use the WPAPI client by accessing it from
the global WP object to create a new collection of books.
You can place this and say, "const allbooks = new wp API collections books."
At this point, all books is simply an empty collection, so you will need to fetch the
books by calling the fetch method on the books collection.
The fetch method returns a prompt, so you can chain the done method to handle the response
and implement a callback function which will accept the response from the API request.
Done.
Then set up callback function, make this one anonymous, and it should receive the books
from the response.
Now you can loop through the books using something like the forEach method to access each book
individually.
Let's say, "books for each" This one has another callback function, "book"
And we can do something with each book.
Finally, you can add the book title and permalink to the text area.
First, you need to create an instance of the text area before the forEach loop, and then
append the values to the text area's value property inside the forEach loop.
So the text area's id is "box store book list"
So we can say, here before the loop, we can say "const text area document get element
by id 'book store list' text area value 'book title' and comma"
And then append the book, concatenate that with a book link, then concatenate that with
a comma, and a new item too.
Your final code will look something like this.
Switch back to the custom booklist admin page and click the Loads Book button to see the
list of books appear in the text area.
Since the inclusion of the block editor in WordPress 5.0, the WordPress Fetch API package
has also been made available to make REST API requests.
This package is a wrapper around the browser Fetch API and provides a more modern and flexible
way to make requests to the REST API.
To make use of the Fetch API, you can update your plugin's JavaScript dependencies to include
WP API Fetch.
You can either remove the WP API dependency or add WP API Fetch as an additional dependency.
Add a button to the actions area of the form to trigger the new Fetch request.
As before, in your bookstore.js file, set up an event listener on the click event of the
new button.
At this time, use the API Fetch method to make the request to the REST API.
Here we have the button variable and the event listener on the button.
Then we can call the API Fetch method on the WP object.
And we'll pass in an object, path property, pointing to the REST API endpoint.
Notice how you pass the path to the box endpoint in an object to the WP API Fetch function.
This is more flexible than using the Backbone.js client, which requires you to use a specific
election to access the box.
You can chain a then method to handle the response.
This is similar to the use of the done method in the Backbone example, in that it returns
a promise that waits for the request to the REST API to complete, and then returns the
result to the callback function specified.
Inside the callback function, you can access the box object and loop through it using the
map method to append the book title and permalink to the text area.
So first we can get the text area and then map through the box object.
And append the title and link to the text area.
You'll notice that this code is using the arrow function syntax for the callback functions,
which is a more modern way of writing functions in JavaScript.
If you refresh your admin page and click on the Fetch Books button, it should now return
the box in the list.
If you're developing blocks, there is also a Core Data package available to access data
from the REST API.
Core Data is meant to simplify access to and manipulation of Core WordPress entities when
developing blocks.
It registers its own store and provides a number of selectors which resolve data from
the WordPress REST API automatically, along with dispatching action creators to manipulate
data.
Core Data makes use of a number of Core React functionalities, so it's best used in a block
context.
Let's look at how you could use the Core Data module in a block to fetch books from the
REST API.
First, using the create block tool you learned about in the introduction to block development
module, create a new block called Bookstore block.
So we'll start by switching to our sites plugins directory.
And then we'll run "mpx@wordpress.com" create "block@latest" and we'll call it Bookstore
block.
This will scaffold a new block with some code for you to int.
Inside the blocks edit.js file, import the "useSelect" hook from the WordPress Data package,
as well as the store from the WordPress Core Data package.
Then you can use these to fetch the books from the REST API in your edit component.
"useSelect" is a hook that allows you to retrieve data from registered selectors.
"useSelect" accepts a callback function as its first argument, where you make use of
the "bookstore stores" entity record selector to retrieve the books from the REST API.
These books are then stored in the "books" variable.
Finally, you can update the code to either return an empty component if no books are
returned or loop through the books object and output the book title and link.
Here we are returning empty div if there are no books.
If there are books we loop through the books, outputting a paragraph with anchor tag and
anchor tag uses the book link and the book title.
Next, run the bold step, then activate the plugin and add the bookstore block to a postal
page.
Then we run npm run bold to run the bold step.
And in WordPress we would activate the bookstore block plugin.
And if we add a new post and add the block, it displays the title with a link to the book.
Differences between the options.
The Backbone.js client is the oldest of the three options, but it is also the most tightly
integrated with the REST API.
If you need to build admin dashboard pages using the WP REST API, it's a good choice,
and far better than using the legacy admin Ajax or PHP endpoint.
API fetch is a great all-round solution, because you can use it for admin dashboard pages,
as well as developing blocks for the editor.
It's also a more modern way to make requests to the REST API, and is more flexible than
the Backbone client.
Or data is best used in a block context, as it uses React functionality that's not available
outside the context of the block editor.
Thank you