Skip to Content

How do I enable WP REST API in WordPress?

The WP REST API allows developers to interact with WordPress sites by sending and receiving JSON data. It provides a powerful way to build mobile apps, JavaScript web apps, external applications, and integrations that all can interact with your WordPress site data.

The WP REST API is included in WordPress 4.7 and later versions. However, it needs to be enabled if you want to start using it.

Why Use the WP REST API?

Here are some of the key benefits of using the WP REST API in WordPress:

  • Build mobile apps for iOS and Android that can display and interact with your WordPress content
  • Create advanced front-end JavaScript applications that leverage your WordPress data
  • Integrate external applications, services, and data sources with your WordPress site
  • Enable interfaces for alternate front-ends like desktop apps, TV apps, watches, etc.
  • Syndicate and distribute content to other platforms
  • Develop plugins that offload processing from PHP to REST API calls

In short, the WP REST API opens up a whole new world of possibilities for integrating your WordPress site with other apps and services. It provides a modern, scalable, and easy way to leverage WordPress as a content backend.

How to Enable the WP REST API

Enabling the WP REST API requires adding some code to your WordPress site’s functions.php file. Here are the steps:

  1. Access your site’s files via FTP, SFTP, or your host’s file manager.
  2. Open the wp-content/themes/your-theme/functions.php file in a text editor.
  3. Add the following code:
add_action( 'rest_api_init', 'my_rest_api_init' );

function my_rest_api_init() {
  // Register custom routes here
  
  // Allow JSON requests
  register_rest_field( 'post', 'authorName', array(
    'get_callback'    => 'get_author_name',
    'update_callback' => null,
    'schema'          => null,
  ) );
}

function get_author_name( $object, $field_name, $request ) {
  return get_the_author_meta( 'display_name', $object['author'] );
}

This code registers a new route and field to the WP REST API that allows getting an author’s display name. You would modify this with your own custom routes and fields as needed.

That’s it! The WP REST API should now be enabled and ready for you to start integrating with.

Testing the WP REST API

To test that the WP REST API is working properly, you can use cURL or a REST API testing tool like Postman.

Here is an example cURL request to fetch a post with the custom authorName field:

curl -X GET https://example.com/wp-json/wp/v2/posts/1?_fields=authorName

The response should contain JSON for the post with the author’s display name returned in the custom field:

{
  "id": 1,
  "authorName": "John Doe"
}

This confirms that the WP REST API has been enabled correctly.

Available WP REST API Endpoints

The WP REST API provides a wide array of default endpoints that allow accessing the majority of WordPress content.

Some of the major ones include:

  • Posts – /wp/v2/posts
  • Pages – /wp/v2/pages
  • Comments – /wp/v2/comments
  • Taxonomies – /wp/v2/categories
  • Tags – /wp/v2/tags
  • Users – /wp/v2/users
  • Media – /wp/v2/media

There are many more endpoints that allow access to custom post types, metadata, settings, and more. See the WP REST API reference for a complete list.

Registering Custom REST API Endpoints

One of the great benefits of the WP REST API is the ability to register your own custom endpoints. This allows you to expose anything in WordPress to the API.

Here is an example of registering a custom endpoint to fetch recent posts by category:

add_action( 'rest_api_init', 'my_rest_routes' );
 
function my_rest_routes() {
  register_rest_route( 'myplugin/v1', '/recent-posts/(?P[a-zA-Z0-9-]+)', array(
    'methods' => 'GET',
    'callback' => 'my_recent_posts',
  ) );
}
 
function my_recent_posts( $data ) {
  $posts = get_posts( array(
    'cat' => $data['category'],
    'posts_per_page' => 5,
  ) );
 
  if ( empty( $posts ) ) {
    return new WP_Error( 'no_posts', 'Invalid category.', array( 'status' => 404 ) );
  }
 
  return $posts;
}

Now a GET request to /wp-json/myplugin/v1/recent-posts/news will return the 5 most recent posts in the “news” category in JSON format.

This is just one simple example of the powerful custom integrations you can build with the WP REST API and your WordPress site.

WP REST API Authentication

By default the WP REST API is only accessible internally or via authenticated calls. There are a few ways to enable external access:

  • Disable authentication – Adding define( 'REST_API_NO_AUTH', true ); to wp-config.php will disable authentication completely. Useful for development but not recommended for production.
  • Adjust auth permissions – The rest_api_init hook can be used to adjust authentication rules for specific endpoints. For example, allowing unauthenticated access to certain read-only routes.
  • Use API keys – API keys can be generated using plugins like API Key Auth which allows key-based authentication to the REST API.
  • Use OAuth – The OAuth 1.0a Server plugin enables full OAuth 1.0a authentication flows for secure API access.

Proper authentication should be implemented for any production WP REST API usage.

WP REST API Caching

Excessive API requests can slow down your WordPress site. A REST API caching plugin can improve performance by caching responses.

Some options to cache REST API requests include:

  • Transients API – A simple way to implement caching directly in your custom API endpoint code.
  • WP REST Cache – Caches routes for specified times and purges automatically on content changes.
  • REST Cache – Supports caching, rate limiting, purging, and more for robust API performance.

Caching is a must for production sites expecting heavy API traffic. Test different caching plugins and strategies to maximize performance.

Using GET, POST, PUT, DELETE HTTP Methods

The WP REST API supports standard HTTP request methods for interacting with endpoints:

Method Description
GET Retrieve data from an endpoint.
POST Create new data via an endpoint.
PUT Update existing data via an endpoint.
DELETE Delete existing data via an endpoint.

For example, you can make a GET request to retrieve posts, a POST request to create a new post, PUT to update a post, and DELETE to delete a post.

Using the proper HTTP methods is important for adhering to RESTful API conventions and security best practices.

WP REST API Security

Security should always be a top priority when providing external access to your WordPress site.

Here are some REST API security best practices:

  • Use HTTPS everywhere
  • Implement proper authentication via API keys, OAuth, etc.
  • Restrict API access to only required endpoints
  • Add rate limiting to prevent brute force attacks
  • Disable unneeded HTTP methods (PUT, DELETE, etc) on endpoints
  • Sanitize input data and escape output
  • Use current PHP and WordPress versions

Security plugins like the REST API Log can help monitor for suspicious API activity. For optimal security, consider implementing a Web Application Firewall (WAF).

Debugging WP REST API Requests

Issues interacting with the REST API can be debugged using various tools and techniques:

  • Browser Developer Tools – Inspect network requests directly within Chrome, Firefox, or Edge developer tools.
  • Postman – Desktop app that allows intercepting and debugging REST API requests.
  • REST API Log – Plugin to log all API requests and responses.
  • WP REST API Explorer – Navigate and test endpoints right within the WordPress admin.
  • Error Details – Enable the rest_api_debug filter to get error details.

Mock REST API services like Mockable can also help mock and test endpoints during development.

Versioning the WP REST API

The WP REST API includes versioning to allow iterating without breaking existing integrations.

The default version prefix is wp/v2 but you can add custom versioning:

// Register route for myplugin/v1 
register_rest_route( 'myplugin/v1', '/recent-posts', array(
	'methods' => 'GET',
	'callback' => 'my_awesome_func',
) );
 
// Register route for myplugin/v2
register_rest_route( 'myplugin/v2', '/recent-posts', array(
	// ...
) );

Now calls to /myplugin/v1/recent-posts will be handle by version 1 logic while /myplugin/v2/recent-posts can include version 2 updates.

Conclusion

The WP REST API provides amazing potential for decoupling your frontend and backend and building complex integrations. While this guide covers the basics of getting started, leveraging the true power of the REST API requires diving deeper into the technical details and possibilities.

I suggest checking out the following resources:

The WP REST API opens up a whole new era and world of opportunities for WordPress. I’m excited to see how you leverage it in your next project!