Understanding the WordPress API

The WordPress API was intruduced some time ago to streamline the ways that we interact with WordPress servers.  I will be documenting my journey with the WordPress API, please come along with me!

To API or not to API

API’s are application programmer interfaces, which allow for the manipulation of data on a server through Hyper Text Transmission Protocols.  There are 4 primary HTTP methods (also called HTTP Verbs) that we must understand:

  • Get – Retreives information from the server
  • Post – Creates a new file on the server
  • Put – Updates an existing file on the server
  • Delete – Deletes a file from the server

Now that we know the methods to interact with the data, we must understand what the server is telling us when it responds to our interactions.  Here are the main Status Codes:

  • 200 – OK -Successful request
  • 201 – Created – File successfully created on server
  • 400 – Bad Request – Couldn’t complete the request
  • 401 – Unauthorized – User did not authenticate
  • 401 – Forbidden – User authenticated but is not allowed to perform action

Choosing Your Routes

Another important concept with API’s is an understanding of routes and endpoints.

  • Routes – Routes point to particlar resources
  • Endpoints – Functions that trigger actions upon resources
    • these actions can be any of the HTTP methods referenced above.

For Example:

A route to your posts on wordpress could be ‘/wp-json/wp/posts’ while the enpoints would be ‘GET /wp-json/wp/posts’ and ‘POST /wp-json/wp/posts’.  The first endpoint triggers a GET method which retrieves posts from wordpress.  The second endpoint creates a new post on the server, while also validating and checking authentication to ensure that the user is allowed to crate the post in the first place.

Another Example:

A route to a specific post (ID = 10) on wordpress could be ‘/wp-json/wp/posts/10’ while the endpoints would be:

  • GET /wp-json/wp/posts/10 – Retrieve the specific post
  • PUT /wp-json/wp/posts/10 – Update the specific post
  • DELETE /wp-json/wp/posts/10 – Delete the specific post

Important Point – Many API’s, including WordPress, treat POST and PUT as identical in that substituting POST for PUT in the previous example would still result in the updating of the specific post.

In these examples, we used a post as our resource, but these same methods, routes, and endpoints will work for any resource, be it a page, post, comment, image, etc.

Get Jumping with JSON

The WP REST API works heavily with JSON ( Javascript Object Notation ) as the format for data interchange, so we must be familiar with the JSON method of representing data.  It is simply a representation of a javascript object, with key – value pairs having the key representing the property name.

For example, a post object has the following keys:

  • id – Integer : {Value of Property}
  • type – String (e.g., post or page) : {Value of Property}
  • slug – String : {Value of Property}
  • url – String : {Value of Property}
  • title – String : {Value of Property}
  • title_plain – String : {Value of Property}
  • content – String (modified by the read_more argument) : {Value of Property}
  • excerpt – String : {Value of Property}
  • date – String (modified by the date_format argument) : {Value of Property}
  • modified – String (modified by the date_format argument) : {Value of Property}
  • categories – Array of category objects : {Value of Property}
  • tags – Array of tag objects : {Value of Property}
  • author Author object : {Value of Property}
  • comments – Array of comment objects : {Value of Property}
  • attachments – Array of attachment objects : {Value of Property}
  • comment_count – Integer : {Value of Property}
  • comment_status – String ("open" or "closed") : {Value of Property}
  • thumbnail – String (only included if a post thumbnail has been specified) : {Value of Property}
  • custom_fields – Object (included by setting the custom_fields argument to a comma-separated list of custom field names) : {Value of Property}
  • taxonomy_(taxonomy) – Array of custom taxonomy objects (these resemble Category or Tag response objects, depending on whether the taxonomy is hierarchical) : {Value of Property}

Important Note – When reading JSON, all string elements will be enclosed in double-quotes, which is the only method supported by JSON (while javascript doesn’t strictly enforce one or the other, with the exception being nesting).

Title and Content values are actually objects containing a property of “rendered“, then the value (title and post content).  The content will be a valid HTML string. Author will be a number referring to the ID of the author.  The categories and tags values are arrays of ID’s the refer to the category or tag ID’s.

JSON returns an array of objects that can then be manipulated at the endpoints.  Therefore, the only valid JSON data is a single object or an array of objects.

XXXML

The other popular alternative to JSON representation of data is XML representation.  It relies on XML tags to represent the key – value pairs.  The problem with XML is that it’s not as efficient and concise as JSON.

Access Your WordPress API

Each installation of WordPress has it’s own wordPress API, available at: domainName.com/wp-json/ .  Placing a get request through Postman returns the website information in JSON format.  We get the following data:

  • name – Website Name
  • description – Tagline for website
  • url – web address
  • home – url where the website is located, not always the same as url
  • namespaces – an array of all the namespaces that are registered by the WP REST API and all plugins and themes.  Namespaces are a way for plugins to avoid overwriting eachother when trying to run their code
  • authentication – array of all authentication methods supported by API
  • routes – lists all supported routes for the WP REST API
    • routes are listed as individual objects
      • inside each route objects are properties for route, including:
        • namespace
        • HTTP Methods
        • endpoints
  • Args – List of all arguments that can be passed along this route
    • take special note of argument datatype
      • if default property contains [], then argument type is an array and we can pass multiple values to it
      • if we have property called “enum”, then argument is enumerated type, so it only accepts predefined elements as valid values.
      • if otherwise, argument type is simple string
  • _links – An array of associated resources based on HAL (Hypertext Application Language)

Down the Rabbit Hole

We just explored the return from the index page, but what if we want to further explore each particular route and understand it’s methods and supported arguments.  For that, we send an options request to that route.  This returns an object with various properties:

  • namespace
  • methods – supported HTTP Methods
  • endpoints – supported endpoints

If we were to run an options request on the posts/ route, we receive 2 supported methods (GET and POST) and multiple arguments, including: (for GET)

  • context – scope
  • page – current page of the collection
  • per_page – number of items to be returned in result set
  • search – limit results to those matching a string
  • after – Limit results to posts published after set date
  • author – Limit results to posts assigned to specific author
  • author_exclude – Exclude posts from specific author
  • before – Limit responses to posts published before certain date
  • exclude – exclude specific post ID’s
  • include – limit results to specific ID’s
  • offset – Offset the result set by a specific number of items
  • order – sort by ascending or descending
  • orderby – sort collection by object attribute
  • slug – limit results to posts with specific slug
  • status – limit results to specific statuses
  • categories
  • categories_exclude
  • tags
  • tags_exculde
  • sticky

For POST

  • date
  • date_gmt
  • slug
  • status
  • password
  • title
  • content
  • author
  • excerpt
  • featured_media
  • comment_status
  • ping_status
  • format
  • meta
  • sticky
  • template
  • categories
  • tags

We also receive the schema for the particular resource.  The schema is a documentation of all the properties supported by the resource.

If you need to explore all supported routes for an API, you want to send a GET request to the index route.  However, if you want to further explore any individual routes, send options request to that route.