How can I enable and customize WordPress REST API for my site?

Linda K Dec 18, 2024 REST API
What do I need to do to make my website work with apps using WordPress data?
What are the steps to enable and customize the WordPress REST API for better integration with external applications?
Andy answered Dec 18, 2024

Enabling and Customizing WordPress REST API

Basic Setup

The WordPress REST API comes enabled by default since WordPress 4.7. Here's what you need to know:

  1. Verify your REST API is working by visiting:
    • yoursite.com/wp-json/ - Should return JSON data
    • yoursite.com/wp-json/wp/v2/posts - Should list your posts

Authentication

For secure API access, you'll need authentication. Here are the main methods:

  1. Cookie Authentication - For logged-in users
  2. OAuth 1.0a - For third-party applications
  3. Application Passwords - Recommended for modern applications

Enable application passwords in wp-config.php:

define('WP_APPLICATION_PASSWORDS_ENABLED', true);

Custom Endpoints

Register a custom endpoint to expose your own data:

add_action('rest_api_init', function () {
    register_rest_route('myapp/v1', '/custom-data', [
        'methods' => 'GET',
        'callback' => 'get_custom_data',
        'permission_callback' => '__return_true'
    ]);
});

function get_custom_data() {
    return ['message' => 'Hello from custom endpoint'];
}

Adding Custom Fields

Add custom fields to existing endpoints:

add_action('rest_api_init', function () {
    register_rest_field('post', 'custom_field', [
        'get_callback' => function($post) {
            return get_post_meta($post['id'], 'custom_field', true);
        },
        'update_callback' => function($value, $post) {
            update_post_meta($post->ID, 'custom_field', $value);
        },
        'schema' => null
    ]);
});

Security Best Practices

  1. Limit Access
add_filter('rest_authentication_errors', function($result) {
    if (!empty($result)) {
        return $result;
    }
    if (!is_user_logged_in()) {
        return new WP_Error('rest_not_logged_in', 'You are not logged in.', ['status' => 401]);
    }
    return $result;
});
  1. Disable REST API (only if absolutely necessary):
add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');

CORS Support

Enable CORS for specific domains:

add_action('rest_api_init', function() {
    remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
    add_filter('rest_pre_serve_request', function($value) {
        header('Access-Control-Allow-Origin: https://trusted-domain.com');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Credentials: true');
        return $value;
    });
});

Helpful Plugins

  1. REST API Toolbox

    • Manage REST API settings
    • Control endpoint access
    • Plugin Link
  2. JWT Authentication

    • Adds JWT authentication
    • Secure token-based auth
    • Plugin Link

Common Pitfalls

  1. Not setting proper permissions
  2. Forgetting CORS headers for cross-domain requests
  3. Exposing sensitive data through custom endpoints
  4. Not sanitizing input data
  5. Not validating authentication properly

Testing Your API

Use these tools to test your endpoints:

  • Postman
  • cURL
  • WordPress REST API Console (debug tool)

Basic cURL test command:

curl -X GET https://yoursite.com/wp-json/wp/v2/posts

Performance Tips

  1. Use caching for API responses
  2. Limit response fields
  3. Implement pagination
  4. Use proper HTTP methods

Cache API responses:

add_action('rest_api_init', function() {
    add_filter('rest_post_collection_params', function($params) {
        $params['per_page']['maximum'] = 100;
        return $params;
    });
});

Remember to test your API thoroughly before going live, especially when implementing custom endpoints or modifying existing ones.