Introduction To The WordPress REST API

Will Johnston Avatar

·

In the modern age of frontend development developers need flexibility in what tools they can use to implement their frontend websites and apps. Prior to the release of the WordPress REST API separating your frontend from WordPress would be a daunting task. With the release of the REST API, WordPress is paving the way for a better future for developers. If you have worked with a REST API before then it shouldn’t be too difficult to get started with the WordPress REST API. If you are new to REST APIs or APIs in general, let’s get acquainted with them before we dive into the WordPress REST API.

What Is A REST API?

An Application Programming Interface, or API, defines a way for multiple computing platforms to communicate. It allows for a computing platform (e.g. a frontend website) to make requests and receive data from another system. The API defines how the requests should be made, what the format of the data will look like, and any conventions that are needed. A REpresentational State Transfer API, or REST API, is a special style of API that comes with a common architecture and patterns used in web services. RESTful web services provide interoperability between web computing platforms over the internet. REST APIs provide URL endpoints where you can request information from a system.

The WordPress REST API

The WordPress REST API provides URL endpoints to request different objects from WordPress such as posts, pages, settings, taxonomies, etc. Transactions with the WordPress REST API are done using JSON, making it easy for JavaScript applications in particular to interact with the API. JavaScript is not a requirement to interact with the API, you can use any language that can make HTTP requests. In general, when you are building a client application separate from WordPress and you want to use some data from WordPress you will need to utilize the REST API.

Using the WordPress REST API

Let’s take a look at the WordPress REST API using only our browser. The simplest request you can make is a GET request to yoursite.com/wp-json/. For example, for my test site I use Local, a popular developer tool for running local WordPress sites. I have my local WordPress site as http://mysite.local/. If I go to http://mysite.local/wp-json/ I see a JSON response showing me a few things:

  1. Some general information about my site (i.e. name, description, url)
  2. What API routes are available
  3. What endpoints are available for each route

The root GET requests actually returns all of the available API routes. If you look closely you will see one route called /wp/v2/posts. This route is the list posts endpoint. Making a GET request to this route will return all of the published posts for the site. I have my site setup with a test post so I can see it in action. Let’s visit this route (i.e. http://mysite.local/wp-json/wp/v2/posts) and make a GET request to see what it returns:

[
  {
    "id": 26,
    "date": "2020-12-18T20:37:13",
    "date_gmt": "2020-12-18T20:37:13",
    "modified": "2020-12-18T20:37:13",
    "modified_gmt": "2020-12-18T20:37:13",
    "slug": "test-post-please-ignore",
    "status": "publish",
    "type": "post",
    "link": "http://mysite.local/test-post-please-ignore/",
    "title": {
      "rendered": "Test Post, Please Ignore"
    },
    "content": {
      "rendered": "<p>This is a test post.</p>",
      "protected": false
    },
    "excerpt": {
      "rendered": "<p>This is a test post.</p>",
      "protected": false
    },
    "_links": {
        "self": [{
            "href": "http://mysite.local/wp-json/wp/v2/posts/26"
        }]
    }
  }
]
Code language: JSON / JSON with Comments (json)

I took the liberty of reducing some of the fields in the response to make it easier to view. Notice the response is a list of posts, and will return multiple posts if you have more than one. Each posts has a standard set of fields such as title, content, excerpt, slug, etc.

If you notice in the JSON response above there is also a “link” to the API endpoint for the post. Making a GET request to the link will return the individual post data as shown below:

{
  "id": 26,
  "date": "2020-12-18T20:37:13",
  "date_gmt": "2020-12-18T20:37:13",
  "modified": "2020-12-18T20:37:13",
  "modified_gmt": "2020-12-18T20:37:13",
  "slug": "test-post-please-ignore",
  "status": "publish",
  "type": "post",
  "link": "http://mysite.local/test-post-please-ignore/",
  "title": {
    "rendered": "Test Post, Please Ignore"
  },
  "content": {
    "rendered": "\n<p>This is a test post.</p>\n",
    "protected": false
  },
  "excerpt": {
    "rendered": "<p>This is a test post.</p>\n",
    "protected": false
  },
  "_links": {
    "self": [
      {
        "href": "http://mysite.local/wp-json/wp/v2/posts/26"
      }
    ]
  }
}
Code language: JSON / JSON with Comments (json)

Note the above response is the same as what is returned for the list of posts, but this time only a single post object is returned rather than a list. Looking at the endpoint you notice that we are making the request for the post using its id property. While this works, it isn’t ideal for a few reasons. Applications typically use URLs to determine what request to make. So if you have a single post page on your site at /posts/{id} you will be able to get the id of the post from the URL and use it to make a GET request to your WordPress site. However, this requires your URLs to have numeric IDs when what you really want is prettier URLs that contain the post slug. WordPress allows you to make requests for posts based on slug (and many other fields for that matter) using the list posts endpoint. For example, to get the post above using the slug we can make a GET request to http://mysite.local/wp-json/wp/v2/posts?slug=test-post-please-ignore. This will return a list of one post with our requested post in it.

Pagination Using the WordPress REST API

By default, the list posts API endpoint will only return the latest 10 posts. As your site grows to eventually have more than 10 posts, you will need to customize your API queries to allow for paginating these posts. You can request up to 100 posts at a time from WordPress using a per_page query parameter, but note that larger queries can hurt your site performance. Let’s take a look at a couple query parameters that are useful for paginating your WordPress posts.

  • ?page=: This parameter specifies which page of results you want (e,g. /wp/v2/posts?page=2 will give you the second page of posts)
  • ?per_page=: This parameter (from 1 to 100) specifies how many posts you want in a page
  • ?offset=: This parameter specifies a numeric offset at which to start your page of posts. So ?page=2 is the same as ?offset=10

When writing your frontend code to utilize pagination you have a couple options. Sometimes you simply want include next and previous links to allow a user to navigate. Other times you want the user to be able to click to a specific page. Depending on your needs you might use the page query or the offset query, but you will also need to know how many pages and/or posts your WordPress site has so you can properly display your pagination controls to you user. To address this, every request you make to the list posts API endpoint returns the following two response headers:

  • X-WP-Total: The total number of posts based on the requested parameters
  • X-WP-TotalPages: The total number of pages based on the requested parameters

Using the above headers you can accurately determine if there are more pages available to request as well as how many more pages and posts exist.

Should You Use the WordPress REST API?

The WordPress REST API is a great starting point if you are attempting to move to use WordPress as a headless CMS. However, the REST API is fairly complicated for a lot of use-cases. Many people use the WPGraphQL plugin, which enabled a more user-friendly GraphQL API on top of WordPress. We recommend giving both a shot and seeing which works best for you.

Further Reading

If you like working with the WordPress REST API and you want to learn more, check out the REST API Handbook.

Check out our other posts to learn about using GraphQL to access the WordPress API.