Thursday, 20 October 2022

An Introduction to the WordPress REST API

When the REST API was finally added to WordPress core, it was the end of a long journey. Many had anticipated this change as the biggest step forward for WordPress in the platform’s history. However, if you’re not familiar with the REST API, you may be confused by what it all means.

In short, the addition of the WordPress REST API turned WordPress into a fully-featured application framework. This significantly increased its ‘extensibility,’ or its ability to be extended with new features and capabilities. Plus, it expanded the platform’s potential for communicating with other sites and applications.

An Introduction to REST APIs

Before we dig deeper into the WordPress REST API, it’s important to get our terminology straight. This is a subject where we’ll need to use a lot of acronyms, so let’s clear those up first.

First and foremost, you’ll need to know what Application Programming Interfaces (APIs) are. In the simplest terms, an API is a means by which one system enables other systems to connect to its data.

For example, when a website adds a Facebook ‘like’ button to a page, it does this by hooking into Facebook’s API. This lets the web page use the API to receive data (the code for the like button) and send data (the like request).

So, what is a REST API specifically? Representational State Transfer (REST) is a type of API specific to web services. It contains a standardized set of instructions and rules, making it easier for all ‘RESTful’ services to connect with each other.

In short, REST APIs enable you to make requests to an external system. One example of this is Twitter. You can use its API to request a certain number of tweets from a specific user. The API will then return the tweets based on your request, which you can embed on your site using HTML and CSS.

These requests are carried out using JavaScript Object Notation (JSON). This is a language specifically designed for sending, receiving, and storing data.

We’re going to cover JSON later in this article, but we recommend taking the time to familiarize yourself with this language upfront. This will help prime you for using the WordPress REST API and understanding some of the concepts we’ll be talking about.

What the WordPress REST API Is (And Why It’s Important)

WordPress Rest API

The WordPress REST API functions in largely the same way as the examples we’ve touched on already. Basically, the WordPress REST API gives you full access to WordPress features from any JSON-compatible framework.

Similarly to how Twitter’s API enables you to retrieve and send tweets, the WordPress REST API can be used to manage posts, users, categories, and much more from external platforms. It lets you use WordPress in a number of previously unprecedented ways.

The REST API was announced all the way back in 2013. It started life as a plugin, meant to be incorporated into the WordPress core by Version 4.1. As so often happens, delays pushed the release back until it was finally implemented into the core with the release of WordPress 4.7 three years later.

This was a long but worthwhile wait for many people who saw the WordPress REST API as an important step forward for the platform. You might be wondering why this addition was such a big deal, especially since a lot of users probably didn’t notice much difference. As it turns out, the inclusion of the REST API was a fundamental change to WordPress for many reasons.

By implementing a REST API, WordPress took a step away from simply being a platform for creating websites. Instead, it’s now become a full-fledged application framework. This means developers can use a WordPress site to create applications for mobile devices and the web or as an information repository.

This shift also enabled WordPress to take a step away from its reliance on PHP. By making WordPress compatible with any JSON-compatible language, the REST API greatly expanded the possibilities for developers, enabling them to use WordPress functionality with practically any framework.

Finally, the REST API provides increased flexibility with the interfaces you can use to work with the platform. It made the admin interface completely optional since you can now interact with your WordPress site entirely through JSON commands.

Now, let’s look at how JSON and the REST API come together to make this possible.

How the REST API and JSON Work Together

By now, you should have a handle on the theoretical aspects of the WordPress REST API. So, let’s look at the more practical side of the technology. The official handbook describes using the REST API as follows:

“The WordPress REST API provides API endpoints for WordPress data types that allow developers to interact with sites remotely, by sending and receiving JSON (JavaScript Object Notation) objects.”

The first word we need to focus on here is “endpoints”. The easiest way to think of an endpoint is as a piece of data or a function that can be called using a JSON request. By default, WordPress provides a huge number of standard endpoints to use, but developers can also create custom endpoints.

To reach an endpoint, you must use a ‘route,’ which takes the form of a normal URL. You can even try this yourself right now.

Go to your own WordPress site, and add /wp-json/wp/v2 to the end of its URL. If your site is http://example.com, you would enter http://example.com/wp-json/wp/v2.

When you load this route, you will reach the endpoint, which in this case, returns all content and meta-data for your site in a (messy) JSON format. By using different routes, you can access different endpoints to get specific types of information and perform various tasks.

There are three primary JSON requests you will use with the REST API, so let’s also take a quick look at them now. They are:

  • GET. This type of request is used for retrieving and listing data from the API. For example, you would use a GET request to return a list of users on your site or compile blog posts from a certain timeframe.
  • POST. This request is used for sending data to the API. It enables you to push new information to WordPress, such as adding new users and posts or updating existing data.
  • DELETE. As the name suggests, this request is used to delete data. This enables you to remove posts, pages, users, and more.

GET and POST can sometimes be used with the same endpoint to achieve different results.

For example, let’s look at the endpoint /me/settings/. If you were to perform a GET request on this endpoint, you would receive a list of the current user’s settings. However, by using a POST request on the same endpoint, you would be able to update the settings instead.

Get Content Delivered Straight to Your Inbox

Subscribe to our blog and receive great content just like this delivered straight to your inbox.

Getting Started with the WordPress REST API

We’re now going to put all of this theory into practice and show you some very basic examples of what you can do with the REST API. This is only a taste to help you become comfortable using the REST API to process requests to WordPress.

For more examples, we recommend checking out the official reference library and the REST API Resources.

The following techniques will require you to use the command line to process JSON requests. This enables you to interact with your WordPress site by using a text-based interface and sending simple commands.

If you don’t have any experience using the command line, we recommend taking some time to learn the basics first. You may also want to use SSH to create the connection with your site.

Finally, when you’re ready, let’s look at some examples of how you can use the WordPress REST API!

1. Return Posts from a Site

While you will obviously need the proper authorization to edit a website, it’s possible to retrieve some information from almost any WordPress site. This is because the REST API is consistent across all WordPress installations.

As we discussed, the main reason that APIs exist is to enable external applications to access some of your data. In this example, we can retrieve a single post from the official WordPress news blog:

curl https://wordpress.org/news/wp-json/wp/v2/posts/1

The ID has been set to 1, meaning that this request will retrieve the very first post on the blog. It might be hard to see since the JSON is not very readable, but among the code, you can spot all the content and meta-data for the post:

retrieve a post from the WordPress blog using the WordPress Rest API

You could then use this information in an application, for example, to display it using your own customized styling.

If you want to return every post from the blog instead, all you have to do is remove the ID at the end. However, it’s more likely that you’ll want to return a select number of posts. The following request will return the latest three posts:

curl https://wordpress.org/news/wp-json/wp/v2/posts/?per_page=3

You can try this out for yourself with other sites, and even your own blog.

2. Update a Post

Now, let’s try to make some changes to WordPress using the REST API. To do this, you will need to be logged in to the site you want to manage. For example, if you’re using SSH, you will need to log in to your server.

In this example, we’ll update an existing post. First, let’s use a request to update the title of the post with the ID of 1:

curl -X POST http://example.com/wp-json/wp/v2/posts/1 -d '{"title":"A Brand New Title"}'

This is pretty self-explanatory. The title argument shows that you’re updating the post’s title, which is followed by the text string containing the replacement.

There are plenty of other arguments you can use to make changes to a post. For instance, you can use a list to assign categories to the post, publish it, or change its contents entirely.

3. Delete a User

Finally, let’s look at how you can remove data using the REST API. In this example, we’ll remove a user from the site. Naturally, you’ll need to be logged in and authorized to manage users before you can use this function.

Then, you can use the following request to delete the user with an ID of 101:

curl -X DELETE http://example.com/wp-json/wp/v2/users/101

This will remove the specified user from the site. You can use the additional parameters to reassign the user’s posts to another user based on their ID. Alternatively, you can force a permanent deletion instead of adding the user to the trash.

Through these examples, you can start to see how the REST API enables you to manage the content on your site and connect to others. If you want to learn more, we recommend digging deeper into the REST API Handbook.

Explore WordPress Development

The WordPress REST API was a huge step forward for the platform, away from its roots and into the future. Developers were excited from day one, but if you weren’t familiar with REST APIs to begin with, you might have been confused about why.

Although the REST API might seem overwhelming for beginners, you don’t need to be an experienced developer to use some basic requests. For example, the API enables you to perform diverse tasks on your own site (or others), such as returning posts, updating posts, and deleting users.

Are you looking for high-performance hosting for your WordPress site? At Dreamhost, our DreamPress managed plans offer professional staging environments, automatic backups, in-built caching, and more. Check out our plans today!

Do More with DreamPress

DreamPress' automatic updates, caching, and strong security defenses take WordPress management off your hands so you can focus on your website.

Managed WordPress Hosting - DreamPress

The post An Introduction to the WordPress REST API appeared first on Website Guides, Tips & Knowledge.



source https://www.dreamhost.com/blog/tutorial-wp-rest-api/

No comments:

Post a Comment

Creating and Mastering GA4 Explorations

In the switch from Universal Analytics (UA) to Google Analytics 4 (GA4) — which will go fully into effect July 2023 — a lot of things have...