WP REST API: Retrieving Data

In the previous parts of the series, we have been looking at what the WP REST API is and how it can help us build better applications using the WordPress back end. 

Then we looked at two ways to set up authentication on the server for generating authenticated requests. The first is the basic authentication method, which is useful in development environments and allows rapid prototyping as it doesn’t require much time to set up. The second method of authentication is OAuth 1.0a, which is recommended for production environments as it is much more secure than the basic authentication method.

Now that we have learned how to set up authentication, we are ready to generate authenticated requests to unleash the full power of the WP REST API. We will be using basic authentication throughout this series due to its ease of use, but it’s recommended that you use OAuth 1.0a authentication, as provided by the OAuth 1.0a plugin, for your production servers.

In the current part of the series, we will get our very first hands-on experience with the WP REST API plugin. We will:

  • analyze the structure of a GET request
  • check out how the OPTIONS request self-documents the API
  • send requests to the server for data retrieval
  • analyze the server response that includes properties, schema, and links

So let’s begin by analyzing the structure of a simple GET request.

Anatomy of a GET Request

Before we delve into the details of retrieving any data with the WP REST API, we need to familiarize ourselves with the syntax of a request that is sent to the server. This will lay a solid foundation for our future interactions with the WP REST API.

Consider the following request sent to the server:

The type of request we are sending is GET—one of six HTTP verbs we looked at in the initial part of this series. A GET request is used to retrieve data from the server. Hence, when executed at the server, the above request retrieves a collection of all post objects in the form of JSON data.

Considering the request URI, we can break it into the following parts:

  • http://localserver/: The URL of my local development server. It could be any URL depending on where your WordPress installation is located.
  • /wp-json: It is the endpoint prefix of the WP REST API.
  • /wp: The namespace of the WP REST API plugin.
  • /v2: It is the version of the WP REST API plugin.
  • /posts: It is the resource that we want to retrieve from the server.

The namespace prevents the overriding that might occur when running multiple plugins with each providing its own abstraction layer for the RESTful API. Hence, each abstraction works in its own boundary without affecting the methods and properties that belong to some other abstraction.

The namespace and version were not present in the legacy version 1.2 of the plugin. So in the legacy version, the above request would be like this:

But we will not talk about backward compatibility here. If you want to learn about all the changes that occurred between version 1.x and 2.x, you can find them on the official page.

In addition to retrieving a collection of resources (posts) using the above URI, we can also retrieve a specific resource by mentioning its ID:

The above request will return a post object as it looks down for a post resource that has an ID of 100.

Other times, we also need to search for posts that meet some specific criteria. For that purpose, the WP REST API provides a way using the filter[] syntax:

By sending the above request, we can retrieve all the posts belonging to a category of ID 1. The filter syntax can be particularly helpful when querying posts or navigating between different resources, e.g. posts and categories, using their relations.

Finally, when dealing with arguments that take arrays as input in filter[] syntax, we can append an empty set of square brackets to express arrays like so:

The above syntax is equivalent to the following WP_Query():

Hence, the above GET request will retrieve a list of posts that belong to both categories having an ID of 1 and 2. The same syntax can also be used for array arguments having more than two elements. Please note that the use of the category__and parameter requires user authentication with edit_posts privileges.

We will look into the filter[] syntax in more detail in a later section.

Now that we have learned about formatting a GET request and providing its parameters, it’s time to take a look at the OPTIONS request. An OPTIONS request makes it easy to navigate through the API and actually serves as a self-documenting way to make the API more accessible by documenting all the available HTTP methods on an endpoint, and in turn, the arguments they support.

Navigating Through the API Using the OPTIONS Request

As mentioned before, the OPTIONS request can be extremely helpful in exploring the API. It mentions all the endpoints that belong to a certain route and provides a list of parameters these endpoints support for CRUD operations.

Let’s send an OPTIONS request to the /wp/v2/posts route to check which endpoints it supports and which parameters we can pass along the GET request to query data:

I’ve used cURL to send the above request, but you can use any tool of your choice, including Postman. Be sure to include the full path to the above route, including the path of your server.

The above OPTIONS request to the /wp/v2/posts route returns data in the JSON format that contains five properties:

  1. namespace
  2. methods
  3. endpoints
  4. schema
  5. _links

The namespace property identifies the namespace of the current plugin. In our case it’s wp/v2, signifying version 2 of the WP REST API. We have already looked at the namespace and the purpose it serves in the previous section.

The methods property contains an array of all the methods supported by the current route. By looking at the response the above request returned, it’s clear that the /wp/v2/posts route supports two methods, namely GET and POST. It means that we can use the /wp/v2/posts route to retrieve posts, as well as creating a new post. We will deal with the POST method in the next part of this series, so let’s just focus on the GET method for the time being.

The next property—endpoints—contains an array of the supported endpoints for the current route. This property is directly linked to the previously mentioned methods property as it lists endpoints for the supported methods.

The endpoints property contains object values that in turn contain two properties, namely methods and args. The methods property contains an array of HTTP methods, and the next args property contains all the supported arguments for these methods. These are the arguments that we send along the request in the form of URI parameters.

Looking at the arguments supported by the GET method, we come across nine arguments that include contextpageper_page, etc. These argument objects contain two properties, required and default. The required property indicates whether the argument is required, and the default property represents the default value of the argument.

The schema property in the returned response documents all the properties for the current resource. The schema defines a structure for data in the JSON format. The schema format used in the WP REST API is based on draft 4 of the JSON schema specifications.

The last _links property holds an array of objects containing the links of associated resources. The key in the object specifies the relationship type (e.g. author, collection, selfcomments, etc.), with its value being the link to that associated resource. This linking standard is based on HAL (Hypertext Application Language). You can find more about HAL by reading the specifications authored by Mike Kelley.

In a similar manner, we can send an OPTIONS request to other routes, including those of users, comments, media, pages, etc., to check their supported methods and arguments. OPTIONS requests are your best friend when working with the WP REST API.

The WP REST API provides yet another way to assess the API availability by sending a GET request to the /wp-json index route. This will list all the routes and their endpoints along with their supported methods and arguments.

The above request will return a response object containing a routes property as follows:


This feature is immensely powerful as it lists all the routes and their supported methods and arguments, thus eliminating the need for all these to be documented externally. We will be referring to this response object when performing CRUD operations on different resources.

Having looked at our options to explore the API, let’s now begin working with the WP REST API to retrieve data from the server.

Working With Posts

By now, we have familiarized ourselves with the OPTIONS request, which is a self-documenting way to assess the API availability. We also looked at how it shows supported methods and arguments for a given route. Using this knowledge, we are now ready to retrieve different resources from the server using the WP REST API.

The resource we will begin with is the Posts resource, since it’s the main building block of WordPress. We will deal with retrieving posts using different filters. Applying this knowledge, you will be able to query posts using the WP REST API just as you do with the WP_Query() class.

Throughout this series, we have been working with the Posts resource to demonstrate example requests and their responses, and we already know how to retrieve post collection and an individual post by its ID. So we won’t be covering that again. Instead, we will look at some more advanced ways to retrieve posts using the top-level parameters and the filter[] syntax.

Working With Top-Level Parameters

The WP REST API exposes some of the most commonly used query variables for posts directly on the GET endpoint. These parameters are:

  1. context: The scope of the request. Possible values could be viewembed or edit.
  2. page: The current page of the post collection.
  3. per_page: Total number of posts per page.
  4. search: The search query. Limit results to the matching string.
  5. author: The author ID. Used to limit results belonging to a specific author.
  6. exclude: An array of post IDs to exclude from search results.
  7. include: Limit the results to post IDs specified in this array.
  8. offset: Offset the search results by specified number.
  9. order: The order of the collection. Can either be asc or desc.
  10. orderby: Sorting attribute of the collection. Possible values can be idtitle or slug.
  11. slug: Limit the results to a post having a specific slug.
  12. status: Used to limit the collection of the posts having a particular status.

The context parameter is used to fetch posts depending on the scope we are working in. If we are just listing posts on some index page, then we are good to go with the view context. But if we are retrieving posts in order to edit them, then we need to use the edit context:

The edit context parameter introduces an additional raw field in fields like titlecontentexcerpt, etc. The value of this raw field can be echoed out in the editor for editing the content.

Edit context

Using the edit context requires you to be authenticated as a user with edit_posts privileges.

Using embed as the value of the context parameter fetches the collection of the posts with a minimal subset of their properties.

The other parameters mentioned above are pretty self-explanatory, and you can play around with them in your HTTP client.

These were the basic parameters that allow you to query posts based on certain criteria. To narrow down our querying capabilities, the WP REST API provides the filter[] syntax that supports a subset of the WP_Query() args.

Using the filter[] Syntax

In addition to retrieving a collection of posts using some basic top-level parameters, the WP REST API exposes some of the WP_Query() variables using the filter[] syntax. By using this syntax, we can query posts the same way as we do when working with the WP_Query() class.

Pagination parameters are the most important of all the filters, as they are used extensively on the post listing pages. The pagination parameters allow us to show a specific number of posts per page and navigate to a specific number of pages containing posts.

By default, a GET request retrieves a collection of 10 posts per page. Let’s see how we can submit a GET request to retrieve only five posts per page:

The above request uses the posts_per_page variable that you might be familiar with if you have worked with WP_Query().

The paged parameter is used in conjunction with the posts_per_page parameter, and it’s used to navigate to a specific number of pages. After having retrieved five posts per page, we would make the following request to navigate to the second page:

The posts_per_page and paged filters can be extremely handy when working to build pagination on listing pages using the WP REST API. These two parameters are equivalent to the per_page and page top-level parameters. Hence, the following request does the same work as the above one:

In addition to the collection of posts the above request returns, the server also returns a number of headers with a response that contains useful information, including the total number of posts and the number of pages. These values are contained in the X-WP-TotalPages and X-WP-Total response headers.

Response headers

The X-WP-TotalPages and X-WP-Total response headers are extremely useful when creating pagination using the WP REST API as they list the total number of pages and the total number of posts respectively.

Apart from pagination filters, the other most important usage of the filter[] syntax is to be able to query posts by their dates. For this purpose, the filter[] syntax supports eight parameters, the same as those of the WP_Query() class:

  1. year: The four digit year (e.g. 2015 or 2016)
  2. monthnum: The number of the month from 1 to 12
  3. m: Six digit year-month (e.g. 201601)
  4. w: The week of the year from 0 to 53
  5. day: The day of the month from 1 to 31
  6. hour: The hour of the day from 0 to 23
  7. minute: The minute of the hour from 0 to 60
  8. second: The second of the minute from 0 to 60

So if we are looking for the posts published on the date 2015-10-15 (yyyy/mm/dd), this can be achieved by the following query:

A similar query can be prepared with the help of the above parameters if we need to narrow down our search to the exact hour and minute.

We have already seen in a previous section of this tutorial how we could fetch posts belonging to a specific category or multiple categories using the filter[cat] and filter[category__and] parameters. Now we will use the filter[category__in] parameter to show posts belonging to categories having an id of 5 and 6:

The above request will retrieve a list of all the posts belonging to categories having an id of 5 and 6.

The opposite effect could be achieved by using the filter[category__not_in] parameter in the following manner:

This will retrieve a list of post while excluding all those posts belonging to categories having an ID of either 5 or 6.

More could be written on using the filter[] syntax, but I won’t be covering all that here. You can find a list of all the query variables supported by the filter[] syntax in the official documentation of version 1 of the plugin. A large part of this information is still valid with version 2 of the WP REST API, but it's still lacking in some areas. At the time of writing this tutorial, the official documentation of version 2 doesn’t state anything about the filter[] syntax and the query vars it supports, but we can hope to see improvements in the official documentation in the near future since there are a number of people (including myself) contributing to the plugin development and documentation.

Now that we have looked at different options when querying posts with the help of the WP REST API, we are ready to further advance our journey and look at some other resources supported by the WP REST API.

Working With Post Revisions, Categories, Tags and Meta

Post revisions provide a way to view and restore edits made to a post. The WP REST API provides a way to view all the revisions of a post by querying the /posts/<id>/revisions endpoint. Hence for a given post having an ID of 10, all the revisions can be retrieved by sending the following request:

The above request will return an array containing revision objects. The revisions object contains a subset of properties found in the post object. Below is an example revision object in Postman:

Post revision

A specific revision can be retrieved given that we know its id. So a revision having an ID of 2 with post having an ID of 10 can be retrieved by the following object:

The above request will return a single revision object.

Other than post revisions, categories for a specific post can be retrieved by the following request:

And for the tags, we use the following request:

With <post_id> being the ID of the post.

If we need to retrieve post meta for post having an ID of 10, we send the following request as an authenticated user:

This will return an array of meta objects.

Please note that to work with post and page meta in WP REST API, you need have the companion plugin installed available on GitHub by the WP REST API team.

Working With Other Resources

By now, we have gained a pretty solid foundation for working with the WP REST API to retrieve data. We have already looked at the options request and how it helps us explore the API without the need for external documentation. 

You can always send an OPTIONS request to a particular resource and check what endpoints and parameters it supports. If you need to list all the routes that the WP REST API provides, you can send a GET request to the index endpoint at /wp-json as we learned to do at the beginning of this tutorial.

Considering this advantage of self-documentation, I don’t think that we further need to explore each individual resource in this tutorial, as you are now able to do that on your own.

What’s Up Next?

In this lengthy tutorial, we learned to explore the API using the OPTIONS request as well as retrieve data from the server using the WP REST API. We just looked at a handful of resources including posts, post revision and post meta, as we couldn’t cover all the supported resources in just one tutorial. But you should now be able to explore the API on your own using the techniques we learned in this tutorial.

WordPress has an incredibly active economy. There are themes, plugins, libraries, and many other products that help you build out your site and project. The open source nature of the platform also makes it a great option from which you can better your programming skills. Whatever the case, you can see what all we have available in the Envato Marketplace.

In the next installment of this series, we will learn to perform the other three operations of CRUD, i.e. create, update, and delete resources. So stay tuned...

Tags:

Comments

Related Articles