# Fix WordPress REST API Error

The block editor (Gutenberg) relies heavily on the WordPress REST API. When REST API fails, you'll see errors like "The response is not a valid JSON response," "Updating failed," or the entire editor becomes unusable. REST API issues also affect plugins, themes, and mobile apps that communicate with WordPress.

Diagnose REST API Issues

Test REST API Endpoint

```bash # Test basic REST API curl -I https://yourdomain.com/wp-json/

# Should return 200 OK with JSON content-type

# Test specific endpoint curl -s https://yourdomain.com/wp-json/wp/v2/posts | head -100 ```

Check via WP-CLI

```bash # List available routes wp rest route list

# Test post endpoint wp rest post list --fields=id,title

# Check REST API status wp eval 'rest_preload_api_request("GET", "/wp/v2/posts");' ```

Browser DevTools Check

  1. 1.Open the block editor
  2. 2.Open DevTools (F12) > Network tab
  3. 3.Look for failed requests to wp-json
  4. 4.Check response headers and content

Common REST API Errors

1. 404 Not Found on /wp-json/

REST API routes aren't registered or permalinks are broken.

Fix: Flush rewrite rules

bash
wp rewrite flush --hard

Fix: Check permalink structure

```bash # Set permalink structure wp rewrite structure '/%postname%/'

# Flush wp rewrite flush --hard

# Verify .htaccess cat .htaccess | grep -A10 "BEGIN WordPress" ```

2. 401 Unauthorized / 403 Forbidden

Authentication failing or permissions denied.

Check nonce issues:

bash
# Check if REST nonce is valid
wp eval 'echo wp_create_nonce("wp_rest");'

Fix cookie authentication:

php
// In wp-config.php, ensure these are set correctly
define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);
define('COOKIEPATH', '/');
define('SITECOOKIEPATH', '/');

Check for security plugin blocking:

```bash # Temporarily deactivate security plugins wp plugin deactivate wordfence wp plugin deactivate iThemes-security wp plugin deactivate sucuri-scanner

# Test REST API again curl -I https://yourdomain.com/wp-json/ ```

3. "Not a Valid JSON Response"

Server returning HTML or error instead of JSON.

Check for PHP errors:

```bash # Enable debugging wp config set WP_DEBUG true --raw wp config set WP_DEBUG_LOG true --raw

# Check error log tail -f wp-content/debug.log

# Test endpoint curl -s https://yourdomain.com/wp-json/wp/v2/posts ```

If you see HTML error page instead of JSON, there's a PHP error.

Fix common PHP errors:

bash
# Check for syntax errors
php -l wp-includes/rest-api.php
php -l wp-content/themes/$(wp theme list --status=active --field=name)/functions.php

4. CORS Errors

Cross-origin requests blocked.

Fix CORS headers:

php
// In theme's functions.php
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://yourdomain.com');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Headers: Authorization, Content-Type');
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit;
        }
        return $value;
    });
});

For development only:

php
header('Access-Control-Allow-Origin: *');

5. REST API Disabled

REST API might be disabled by filter.

Check if REST API is disabled:

bash
wp eval 'echo rest_api_enabled() ? "enabled" : "disabled";'

Find disabling code:

bash
grep -r "rest_api_disabled\|rest_enabled" wp-content/ --include="*.php"

Re-enable:

php
// In functions.php or must-use plugin
add_filter('rest_authentication_errors', function($result) {
    return $result;
});

6. JWT Authentication Issues

If using JWT authentication:

```bash # Test JWT endpoint curl -X POST https://yourdomain.com/wp-json/jwt-auth/v1/token \ -H "Content-Type: application/json" \ -d '{"username":"admin","password":"password"}'

# Should return token ```

Fix JWT issues:

php
// Ensure JWT_SECRET_KEY is defined
define('JWT_SECRET_KEY', 'your-secret-key');

7. REST API Requires Authentication

Public endpoints returning 401.

```bash # Check public endpoints curl -s https://yourdomain.com/wp-json/wp/v2/posts?per_page=1

# If 401, check for restrictive filters wp eval ' add_filter("rest_authentication_errors", function($result) { var_dump($result); }); ' ```

8. ModSecurity Blocking

```bash # Check if ModSecurity is active apache2ctl -M | grep security

# Disable temporarily sudo a2dismod security2 sudo systemctl restart apache2

# Test REST API curl -I https://yourdomain.com/wp-json/ ```

Add exception in ModSecurity for wp-json.

Nginx-Specific Issues

Missing try_files

```nginx location / { try_files $uri $uri/ /index.php?$args; }

# For wp-json location ~ ^/wp-json/ { try_files $uri $uri/ /index.php?$args; } ```

FastCGI Parameters

nginx
location ~ \.php$ {
    fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTP_AUTHORIZATION $http_authorization;
    include fastcgi_params;
}

The HTTP_AUTHORIZATION parameter is crucial for REST API authentication.

Apache-Specific Issues

.htaccess Blocks

```bash # Check for wp-json blocks grep -i "wp-json|api" .htaccess

# Ensure REST API is allowed # WordPress .htaccess should handle this ```

AllowOverride

Ensure AllowOverride is All for REST API rewrites:

apache
<Directory /var/www/html>
    AllowOverride All
</Directory>

WordPress Multisite Issues

On multisite, REST API URLs include the site path:

```bash # Site-specific REST API curl -I https://yourdomain.com/site1/wp-json/

# Or with domain mapping curl -I https://site1.com/wp-json/ ```

Fix multisite REST API:

```php // In wp-config.php define('COOKIE_DOMAIN', false);

// For subdirectory multisite define('PATH_CURRENT_SITE', '/'); ```

Plugin Conflicts

REST API issues often come from plugins.

```bash # Deactivate all plugins wp plugin deactivate --all

# Test REST API curl -I https://yourdomain.com/wp-json/

# Reactivate one by one wp plugin activate plugin-one # Test wp plugin activate plugin-two # Test ```

Common Problem Plugins

Plugins that commonly affect REST API:

  • Security plugins (Wordfence, iThemes Security)
  • Caching plugins
  • REST API controllers
  • JWT authentication plugins

Debug REST API

Enable REST API Debug

```php // In wp-config.php define('WP_DEBUG', true); define('WP_DEBUG_LOG', true);

// In functions.php - log REST requests add_action('rest_api_init', function() { error_log('REST API accessed: ' . $_SERVER['REQUEST_URI']); });

add_filter('rest_pre_dispatch', function($result, $server, $request) { error_log('REST request: ' . $request->get_method() . ' ' . $request->get_route()); return $result; }, 10, 3); ```

Test Authentication

```bash # Test with application password curl -X GET "https://yourdomain.com/wp-json/wp/v2/users/me" \ -H "Authorization: Basic $(echo -n 'username:app_password' | base64)"

# Create application password via WP-CLI wp user application-password create admin "REST API" ```

Check REST Response Headers

bash
curl -I https://yourdomain.com/wp-json/
# Should include:
# Content-Type: application/json; charset=UTF-8
# X-Robots-Tag: noindex
# Link: <https://yourdomain.com/wp-json/>; rel="https://api.w.org/"

Fix Block Editor REST API Issues

The block editor heavily depends on REST API.

Common Block Editor Errors

bash
"The response is not a valid JSON response."
"Updating failed."
"Publishing failed."

Fix 1: Check site URL consistency

```bash # Ensure both URLs are HTTPS and match wp option get siteurl wp option get home

# Fix if needed wp option update siteurl 'https://yourdomain.com' wp option update home 'https://yourdomain.com' ```

Fix 2: Check nonce in REST requests

bash
# Verify nonce is being sent
wp eval 'echo wp_create_nonce("wp_rest");'

Fix 3: Clear object cache

bash
wp cache flush

Fix 4: Disable Gutenberg plugins

bash
wp plugin deactivate gutenberg

Verification

After fixes, verify REST API works:

```bash # Test basic endpoint curl -s https://yourdomain.com/wp-json/ | jq '.name'

# Test posts endpoint curl -s https://yourdomain.com/wp-json/wp/v2/posts?per_page=1 | jq '.[0].title'

# Test block editor loads curl -I https://yourdomain.com/wp-admin/post-new.php ```

Quick Reference

ErrorCauseFix
404 on wp-jsonRewrite rulesFlush rewrite rules
401 UnauthorizedAuthenticationCheck nonce/cookies
403 ForbiddenSecurity pluginWhitelist wp-json
Invalid JSONPHP errorCheck debug.log
CORS errorMissing headersAdd CORS headers
TimeoutServer limitsIncrease PHP limits

REST API issues cascade to the block editor. Start by testing the raw REST endpoint, then work through authentication, plugins, and server configuration to find the blocker.