While the WordPress REST API is commonly used to fetch data from WordPress,
it can also be used to perform other actions.
The REST API also allows you to create, update and delete various WordPress data types.
In this lesson you'll learn about the WordPress REST API schema,
methods to authenticate a WordPress REST API request,
tools to test REST API requests,
as well as a couple of ways to add, edit or delete data via the REST API.
If you skipped the previous lessons in this module, download version 1.0.1
with the bookstore plugin from the link in the repository readme
and install and activate the plugin on your local WordPress install.
When working with the REST API, it's useful to keep the endpoint reference section
of the REST API documentation handle.
The endpoint reference lists all endpoints that ship with WordPress call.
Clicking on an individual endpoint, say posts,
will show you the schema for that endpoint.
The schema defines all the fields that exist for a resource when fetching or creating data of that
specific type. If you've created a custom post type like the books custom post type from the bookstore
plugin, the schema for the custom post type endpoint will be similar to that for the post
endpoint. You'll notice that many of the fields match up with the fields that are available in
the WordPress database table related to that data type. Some, however, are slightly different.
For example, the title field for the post endpoint will match up to the post title field in the post
table. It's important to remember that these differences exist and to use the correct field
name when interacting with the API. By default, the WordPress REST API uses the same cookie-based
authentication method that is used when logging into the WordPress dashboard. For any REST API
endpoints that are not public or require an authenticated user to view or modify,
the authentication cookie needs to be present. This is how the block editor works, for example.
There are a number of ways to authenticate requests, including JSON web tokens and OAuth.
Another way that's built into WordPress is Application Passwords. Application passwords
can be set on a per user basis and are used to authenticate requests to the WordPress REST API.
This allows you to let specific users access the API without having to share the password they use
to log in to the WordPress dashboard. To create an application password for a user,
navigate to the user in the users list and click on the user to edit it.
Now, scroll down to the bottom of the screen under the Application Passwords section.
Give the new application password a name and click the Add New Application Password button.
The password will be generated for you. Make sure to copy it and store it somewhere securely,
as you won't be able to see it again. In this screen, you're also able to revoke the password
should it ever be leaked. Using an application password for your user is a great way to test
out REST API requests using a REST API testing tool. If you intend building something more complex,
like a mobile app that connects to the WordPress REST API, you should rather consider using JSON
web tokens or OAuth. There are a number of tools available to test REST API requests.
For example, if you use PHPStorm, it has a built-in HTTP client. And if you use VS Code,
there are extensions like Postcode. There are also standalone tools like Postman.
You can even test your REST API endpoints using the call command in your terminal.
For the purposes of this lesson, you'll learn how to use Postman to test some REST API requests.
You can download Postman from the Postman website. By default, Postman will create an
initial workspace to store your request collections. Once installed, open Postman and click on the
Create Collection button. This will create a new collection where you can add multiple requests to
test. You can give the collection a name to differentiate it from other collections.
Inside the collection, click the Add Request button.
This will open up a new request where you can give the request a unique name.
Then enter the URL to your local book's endpoint and click the Send button.
The request will be made and the JSON response will be passed and displayed in the response area.
Now, create a new request and enter the same URL to the book's endpoint.
But this time, change the request method to Post and hit Send.
What we can do is we can duplicate the GET request.
Rename it and change the method.
This time, you'll be presented with an error message because you're not authenticated.
To authenticate the request, click on the Authorization tab and select Basic Auth from the drop-down.
Then enter your username and the application password you created earlier and click the Save button.
Then hit Send to save the request.
This time, you don't get the same error because you're not authenticated, so you can create books.
Go ahead and create a book by clicking on the Body tab in the request and selecting the Raw Radio button.
Then select JSON from the drop-down and enter the following JSON.
The title is My Postman Book, the content is This is My Postman Book and the status is Publish.
Hit Send again and the book will be created, returning the JSON response of the new book.
To be sure, go and check the list of books in the WordPress dashboard and you should see the book.
My Postman Book. To update a book, you use the same request configuration to add a book.
But you change the endpoint URL to include the book ID.
To delete a book, you use the same endpoint URL as updating a book,
but you change the request method to delete and don't send any data in the request body.
You'll also notice that deleting a book actually moves it to the trash and doesn't permanently
delete it. This matches the behavior of the WordPress dashboard. Using a tool like Postman
to test REST API endpoints is a great way to learn how to use the REST API.
It's also extremely useful for testing REST API requests by ensuring that the data you intend to
send is formatted correctly and the request is being made to the correct endpoint. Let's use
the WordPress REST API and API fetch to create a new book. To do this, you'll need to pass the
title and content fields in a post request to the book's endpoint. You already have a plugin that
allows you to list books, so you can use that as a starting point. You'll need to update the page
with a form that will allow you to enter the title and content of the book you want to create.
You can use the following HTML to create the form and add it to the admin page callback.
So just underneath this div, you can pop in the form. This HTML code adds a new form to the custom
admin page that allows you to enter a title and content for the new book. The form also includes
a button to submit the form. With this code added, the next step would be to add JavaScript that will
handle things when the button is clicked. Start by copying the fetch code
and then simply updating it for the submit button.
Now that you have the button click of "end listener added",
you can add the code that will handle the creation of the book.
To do this, it's a good idea to create a separate function to create the book and then call that
function on the click event. So the first thing you need to do is to create the submit book function.
Then update the click event listener to call that function.
Inside the submit book function, you'll need to get the title and content values from the form
fields. Start with the title and use document, get element by id and then get the id of the field
and make sure to fetch the value.
In this case, we can duplicate this for content simply by updating the id.
Now you can create the request to the book's endpoint using API fetch by setting the path
to the book's endpoint, setting the request method to post and passing the title and content as a
data object. So to start, let's grab an existing implementation and then remove all the code we
don't need. And then let's update the object sent.
Include method post and the data object which requires the title field and passing the title
variable and then the content field and we'll pass the content variable.
And then once the request is finished, we can just pop an alert of some kind
to the screen. Last but not least, if we want the book to be public, we have to set the status
to published.
Open the custom admin page, enter a title and content and click the add button.
You should see the alert that says "book saved".
Then if you browse the list of books, you should see the new book added to the list.
You can also use the WordPress REST API to update and delete posts. You can use the same
API fetch implementation for updating items as you did for adding items. You need to update the path
to include the id of the data entity being updated, in this case "box", so that it updates that item
as well as the updated data object with the new values for the fields you want to update.
Deleting a post only requires the path to be set to the URL of the item and setting the method
to delete. For more information on creating, adding, updating and deleting entities using
the WordPress REST API, check out the "using the REST API" section in the WordPress REST API handbook
as well as the API fetch package section in the block editor handbook.
[BLANK_AUDIO]