Rest api выдал ошибку вордпресс

By Cameron Pavey

WordPress sites typically use PHP to serve HTML content that’s preloaded with necessary data. However, thanks to the WordPress REST API, this approach is not the only way to build WordPress sites. The REST API allows you to communicate with your site’s backend by sending and receiving JSON objects. You can use it to build powerful themes and plugins for your site that have more dynamic access to data, thus facilitating deeper levels of interactivity. You can even build decoupled frontends using libraries such as React, which then access your site’s data via the API.

In this article, you’ll learn more about the WordPress REST API and the common errors you’re likely to encounter while working with it. You’ll learn potential causes of these errors, as well as some possible solutions.

About the REST API

The WordPress REST API is not required for building a functioning WordPress site, so many developers may not be aware of it or be familiar with what it does. Normally, WordPress sites are built in PHP, including the themes and plugins. This could present an unwanted limitation to developers who would prefer to build their site using a different technology or who want to build a complementary mobile application that uses data from their site.

In these situations, you can use the REST API as a language- and framework-agnostic way of accessing all the same data you would in PHP. The API works with any language that can make HTTP requests and parse JSON responses, encompassing nearly all modern programming languages. Below is an example of the kind of data that is exposed by the REST API:

You can adopt the REST API incrementally—perhaps first using it to add interactivity to your existing WordPress site, then eventually using it to implement a fully custom JavaScript frontend. At this stage, WordPress would essentially act like a headless CMS; it would allow you to keep all of your existing content and plugins while gaining the benefits of a decoupled front end, such as greater flexibility in how you can develop your site.

If you implement the REST API, though, especially when using it on a new site for the first time, you may deal with the occasional error. Some of these errors are common, but fortunately they have simple solutions.

Common REST API Errors

The following are some of the more common errors you might encounter when using the WordPress REST API.

Bad Permalink Settings

One common cause of issues in WordPress is misconfigured permalink settings, which can come up whether or not you’re using the REST API. In this case, when you try to navigate to the REST API endpoint, you’ll be greeted with a 404 error page like this:

There are a few different causes for this. In this particular instance, the issue is some missing apache2 config:

# /etc/apache2/sites-enables/000-default.conf
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    # This following block was missing, thus breaking permalinks
    <Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Another common cause of broken permalinks is having a misconfigured .htaccess file. If you go to your WP Admin dashboard and then navigate to Settings > Permalinks, you can select your permalink style. When you do this, WordPress will attempt to update your .htaccess file accordingly, but in cases where file system permissions prevent it from being able to do so, you will see an error like this:

In this case, you need to either resolve your permission issues or manually update the .htaccess file with the snippet provided by WordPress below the error. Generally speaking, it’s better to update the permission issue if you can. This typically means ensuring that your WordPress installation directory is owned by whichever user the web server is running under (often www-data or nginx) and that the appropriate file and directory permissions are set.

If you have shell access to your server, you can use the following command to find out which user your web server is running under:

ps aux | egrep '(apache|httpd|nginx)'

In this case, you can see that it is running under the www-data user:

With this information, you can update the owner of your WordPress installation by navigating to the appropriate directory and running the following command:

sudo chown -R www-data-www-data .

You may also find that you need to update the actual file and directory permissions if these are currently misconfigured. For more information on doing this, check the official documentation about changing permissions.

Disabled API

The REST API may be disabled on your site. There are some legitimate reasons why you might want this. For example, by default, the API exposes the usernames of those who have posted content on your site. This helps ensure the complete gathering of information. However, it could theoretically be used to assist in a brute force attack against your admin panel, because it gives the attacker some known usernames to try. That can be enough reason for some developers to disable the REST API.

The API could be disabled by custom PHP code or a WordPress plugin that offers such functionality. There are quite a few plugins that offer this ability, generally represented as security-centric. If you suspect an errant plugin may be disabling your REST API access, check for installed plugins in that vein. Some plugins that are known to offer this functionality include:

  • Wordfence Security
  • WP Hide & Security Enhancer
  • Disable REST API
  • Titan Anti-spam & Security
  • WP Cerber Security
  • NinjaFirewall

It is also possible to disable the REST API without a plugin. For example, adding the following snippet to your wp-includes/functions.php file will cause the REST API to cease functioning:

function disable_rest($access) {
        return new WP_Error('access denied', 'REST API Disabled', ['status' => 403]);
}
add_filter('rest_authentication_errors', disable_rest);

Attempts to access the REST API would then return the following response:

Between plugins and custom code, there are countless ways that the REST API could have been manually disabled. If you suspect this is the problem and are unsure where to look, start by disabling all of your plugins (use discretion here, as some plugins may be critical to your site’s functionality) to see if this allows access to the REST API. If it does, start re-enabling plugins until you find which ones are causing the issue.

If no plugins seem to be the cause, you can also look through any custom code that has been added to your site, such as in the functions.php file. Performing a global search for mentions of phrases like “REST” or “API” could be a good starting point, but unfortunately, each site can be so different that if you get this far without finding the cause, you will likely need to commit to some detective work.

General Errors

Another thing to be wary of is common errors and how they can present themselves through the REST API. Ultimately, the REST API is just another interface through which you can interact with your site. This means that when there are mistakes or errors in the code, the REST API is liable to stop working as expected, just like any other code. Consider the following contrived example, in which a hook is used to change the content of all posts to “Some new content”:

function change_post_content( $post_object ) {
        // A contrived example of applying a filter
        $post_object->post_content = 'Some new content' // A missing semicolon
        return $post_object;
}
add_action('the_post', 'change_post_content');

As the comment points out, there is a missing semicolon. The impact of this mistake is quite severe, simply a blank page with no information to guide you toward the cause:

One of the reasons why you won’t get any guidance here is because exposing that kind of low-level information would be a security concern. Thankfully, if you were to check the error logs on the server, in this case found at /var/log/apache2/error.log, you would see that the most recent error says something like:

[Sun Sep 18 10:25:10.145284 2022] [php7:error] [pid 1177] [client 192.168.1.176:44796] PHP Parse error:  syntax error, unexpected 'return' (T_RETURN) in /var/www/html/wp-includes/functions.php on line 8471, referrer: http://wordpress.local/wp-json/wp/v2/posts

This is much more helpful, and quite clearly suggests where the error is.

Another thing to be mindful of is how to manage your own errors. As a developer, you will likely find yourself in a position where you need to add some error handling to a plugin, or to custom code you’re writing. The WordPress documentation has specific guidance around how you should typically deal with errors through the use of the WP_Error class. It is essential to make sure that you don’t just throw exceptions in custom code without handling them, because doing so will typically result in a similar outcome to the previous example, though with slightly different output:

Like the previous example, if you run into something like this, the error logs are a good first place to check. In this case, the logs once again point you to exactly where you need to look:

[Sun Sep 18 10:29:54.862517 2022] [php7:error] [pid 768] [client 192.168.1.176:37230] PHP Fatal error:  Uncaught Exception: Something went wrong in /var/www/html/wp-includes/functions.php:8472\nStack trace:\n#0 
…

Conclusion

The WordPress REST API can add a lot of value to your site by allowing more dynamic ways to access your site’s data. You can use the API to add enhanced interactivity to your site, create new decoupled frontends, or build mobile applications that use your site’s data. There are some common errors that can cause difficulties with your API usage, such as improper permalink settings, incomplete rewrite configs, and security plugins or custom code that disable API access. Fortunately, there are also solutions for these errors.

It’s important to be aware of these issues as you develop your WordPress project. If you decide to use the WordPress REST API, you can easily solve these issues and prevent any inefficiencies or delays in your workflow so that you’re better able to produce high-quality results.

Ошибка REST API стала головной болью для большинства владельцев сайтов на WordPress с того момента, как в панели управления (панели администратора) появился раздел «Здоровье сайта». Тревожное сообщение — «Запрос к REST API неудачен из-за ошибки» — не поддавалось разгадке без специальных знаний в области разработки на PHP. Учитывая, что среди пользователей WordPress программистов чуть больше одной десятой процента, проблема стала актуальной для миллионов менее чем за год.

REST API выдал ошибку — что делать
Решение я нашёл самостоятельно и, без сложных объяснений, сразу перейду к нему.

Ошибка в теме сайта

Способ может показаться слишком простым, но достаточно переключиться на одну из новых стандартных тем WordPress, как сообщение об ошибке REST API исчезает. Возвращаемся к старому дизайну — ошибка возвращается.
Точно также происходит и с другой распространённой проблемой, которая называется «ваш сайт не смог выполнить петлевой запрос». Если в разделе «Здоровье сайта» система сообщает, что «петлевой запрос к вашему сайту не удался. Возможности, зависящие от его работоспособности, не могут работать так, как должны» — знайте, что пришло время менять тему вашего сайта.
уведомление об ошибках REST API

Что делать

Самое действенное решение — установить более современный темплейт. Быстро и радикально, но не всегда подходит. Особенно, если сайту десяток лет, он выстрадан, сбалансирован и его любят посетители. Для таких проектов резкие движения противопоказаны. В этом случае, выбираем более трудоёмкий путь.
Вам нужен прилежный верстальщик, а лучше в паре с талантливым дизайнером, а ещё лучше чтобы с ними рядом трудился над вашим проектом разработчик на PHP. Пара недель (или месяцев) страданий, пара сотен (или тысяч) долларов — и ваш сайт снова молод, свеж и пахуч.

Примечание: сайт, который вы сейчас видите, читая этот текст, работает в паре со стандартной темой «Twenty Fifteen». В данный момент, версия темы — 2.5, но ни сейчас, ни на одной из прежних версий «Fifteen» я ни разу не получал уведомлений об ошибках REST API или петлевых запросов.

Для тех, кто владеет английским языком — документ в формате Portable Document Format (PDF), с полным описанием архитектурного стиля разработки REST и его стандартов.

Тема: REST API выдал ошибку  (Прочитано 9624 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Reply

В админке в Здоровье сайта появились такие критические ошибки:
REST API выдал ошибку
REST API — один из способов коммуникации WordPress и других приложений с сервером. К примеру, экран редактора блоков использует его для отображения и сохранения ваших записей и страниц.
Запрос к REST API неудачен из-за ошибки.
Ошибка: cURL error 28: Operation timed out after 10001 milliseconds with 0 bytes received (http_request_failed)

Ваш сайт не смог выполнить петлевой запрос
Петлевые запросы используются для запуска запланированных заданий, а также используются встроенным редактором кода плагинов и тем для проверки корректности кода.
Петлевой запрос к вашему сайту не удался. Возможности, зависящие от его работоспособности, не могут работать так, как должны.
Ошибка: cURL error 28: Operation timed out after 10001 milliseconds with 0 bytes received (http_request_failed)

Долго не мог понять в чем дело, обновил плагины, тему (у меня дефолтная), одна ошибка пропала, потом появилась снова. ???
Но потом разобрался! Главное не верьте даунам, которые пыхтят о том, что это распространённая ошибка которая связана с сервером. >:(
И что в большинстве случаев она не вызывается ни какой-либо темой, ни плагином, и не самим WordPress. >:(
Что надо дергать хостинг, переходить на ВПС, увеличить лимит и прочую байду!
Это особенно смешно читать, когда на хосте стоит несколько сайтов на WP, но именно один выдает такие ошибки!
Короче, дело не в сервере, никуда переходить и никого дергать не нужно!

Дело именно  ваших плагинах, поскольку это REST API тесно с ними связано. Попробуйте отключать плагины по одному и смотреть что получится. В моем случае это был плагин капчи CheckBot, может быть виновать также плагин WP Limit Login Attempts и другие…
В общем проверяйте сами, а то в интернете сейчас полно умников, которые как чукча, только пейсатели, но ни куя не веб-мастера! >:(


Дмитрий

Здравствуйте. Ваши рекомендации реально помогли! Всё, что я читал на других сайтах не работало. А пробовал я практически всё, что писали. Потерял кучу времени, результат ноль!
Но хорошо, что я попал к Вам на сайт и прочитал отличные рекомендации по поводу отключения плагинов!
На моём сайте, «косяки» были из-за плагина калькулятор. Название: wp-creator-calculator
Спасибо за помощь! Удачи в жизни!



Максим

Большое Спасибо!! Вы очень помогли !!!!


Пожалуйста. :)


Арсений

То есть плагины в прямом смысле удалять? Или можно другим способом сделать?


Не удалять, а отключать по одному в админке и смотреть на результат.




Elskazi

 И правда, помогло, а если этот плагин нужен?:)



Лилия

Reply, респект. У меня это оказался плагин контактной формы. Спасибо ;)


Галин

Всем добрый вечер! У меня та же проблема вылезла. Отключение плагинов по одному не решило проблемы. Что может быть ещё? И как это устранить? Может, кто-то подскажет? Спасибо.


Добрый день.
Такая проблема — это «REST API выдал ошибку»?
Приведите, пожалуйста, текст ошибки/ошибок полностью.


Ali

После отключение плагинов по одному и проверяя, вот результат, сайт перестал загружается.
Warning: Use of undefined constant WPFDL_PLUGIN_FILE — assumed ‘WPFDL_PLUGIN_FILE’ (this will throw an Error in a future version of PHP) in /home/admin/web/itop7.ru/public_html/wp-content/plugins/wp-table-manager-light/wp-table-manager-light.php on line 47

Warning: include_once(.//framework/ju-libraries.php): failed to open stream: No such file or directory in /home/admin/web/itop7.ru/public_html/wp-content/plugins/wp-table-manager-light/wp-table-manager-light.php on line 47

Warning: include_once(): Failed opening ‘.//framework/ju-libraries.php’ for inclusion (include_path=’.:/usr/share/php’) in /home/admin/web/itop7.ru/public_html/wp-content/plugins/wp-table-manager-light/wp-table-manager-light.php on line 47

Fatal error: Uncaught Error: Class ‘Joomunited\WPFramework\v1_0_4\Application’ not found in /home/admin/web/itop7.ru/public_html/wp-content/plugins/wp-table-manager-light/wp-table-manager-light.php:65 Stack trace: #0 /home/admin/web/itop7.ru/public_html/wp-settings.php(388): include_once() #1 /home/admin/web/itop7.ru/public_html/wp-config.php(91): require_once(‘/home/admin/web…’) #2 /home/admin/web/itop7.ru/public_html/wp-load.php(37): require_once(‘/home/admin/web…’) #3 /home/admin/web/itop7.ru/public_html/wp-blog-header.php(13): require_once(‘/home/admin/web…’) #4 /home/admin/web/itop7.ru/public_html/index.php(17): require(‘/home/admin/web…’) #5 {main} thrown in /home/admin/web/itop7.ru/public_html/wp-content/plugins/wp-table-manager-light/wp-table-manager-light.php on line 65
На сайте возникла критическая ошибка.

Прочитайте эту статью про отладку в WordPress, для того, чтобы найти источник проблемы на вашем сайте.


  • Ответ
  • Печать

Страницы: [1] 2   Вверх

В связи с появлением свободного времени, решил Я проверить техническое состояние своего сайта, произвести обновление различных компонентов (WordPress, PHP, MySQl, Apache и т.д) и проверить работоспособность программного обеспечения. Открыв «Здоровье сайта» если кто не знает это встроенный инструмент для диагностики состояния системы и сервера, я увидел сообщение о двух критических проблемах «Обнаружена активная PHP сессия» и «REST API выдал ошибку». Когда появились эти ошибки было не понятно, но думаю достаточно давно так как данный инструмент последний раз Я открывал наверно еще в прошлом году. Влияние этих ошибок на работоспособность сайта было совсем не значительное, так как сайт работал в штатном режиме. Но раз проблемы есть да и еще критические их хотелось решить. Поискав информацию в интернете, Я понял что в большинстве случаем причины появления этих ошибка практически одинаковые, и решение одно и тоже. Сегодня хочу поделиться своим случаем.

WordPress как убрать критические проблемы

И так вы обнаружили следующие критические проблемы на своем сайте.

Обнаружена активная PHP сессия

Сессия PHP была создана вызовом функции session_start(). Это препятствует работе REST API и петлевых запросов. Сессия должна быть закрыта функцией session_write_close() перед выполнением любых HTTP-запросов.

REST API выдал ошибку

REST API — один из способов коммуникации WordPress и других приложений с сервером. К примеру, экран редактора блоков использует его для отображения и сохранения ваших записей и страниц.

Запрос к REST API неудачен из-за ошибки.

Ошибка: cURL error 28: Operation timed out after 10001 milliseconds with 0 bytes received (http_requ

Обнаружена активная PHP сессия

В 99% случаев эти ошибки связаны с установленными плагинами и темами. Что нужно сделать, для начала произвести обновление, если это не поможет то по очереди отключать плагины и проверять состояние, если и это не поможет то нужно переустановить тему. Если тема доработана и переустановка приведет к потери всех изменений то можно просто поменять на стандартную.

Wordpress Здоровье сайта

В моем случае причиной появления ошибок «Обнаружена активная PHP сессия» и «REST API выдал ошибку» стал плагин «Капча».

Wordpress как убрать критические проблемы

После его отключения все критические проблемы пропали.

REST API выдал ошибку

Плагины могут быть причиной и других ошибок и даже замедлять работу сайта. В общем если возникают какие либо проблемы с работоспособностью сайта в первую очередь нужно проверить плагины и установленную тему, это касается в первую очередь WordPress.

Has your WordPress Block Editor’s layout got messed up and doesn’t load properly, and Site Health Status is showing you the performance issue, The Rest API did not behave correctly? You’re in the right place.

In this tutorial, I will guide you on how to fix the layout of WordPress Block Editor by resolving the REST API issue.

The REST API allows you to communicate with your WordPress backend (admin section) by sending and receiving JSON objects. WordPress developers can use REST API to build powerful WordPress themes and plugins that have more dynamic access to your site’s data.

This is the complete detail of, “The Rest API did not behave correctly” issue:

The REST API is one way that WordPress and other applications communicate with the server. For example, the block editor screen relies on the REST API to display and save your posts and pages.

The REST API did not process the context query parameter correctly.

The REST API is one way that WordPress and other applications communicate with the server. For example, the block editor screen relies on the REST API to display and save your posts and pages.

  • This is how the layout of your WordPress Block Editor gets messed up and doesn’t load properly.

The layout of your WordPress Block Editor gets messed up and doesn't load properly.

Following topics will be covered in this post:

  1. Clear your Browser Cache or Check on Another Browser
  2. Enable Cache All Query Strings on CDN Settings
  3. Disable REST API Features on Yoast Plugin
  4. Other Solutions

RELATED

  • How to Migrate Domain and Hosting to Namecheap
  • How to Set Up WP Mail in WordPress to Send Emails

01. Clear Browser Cache or Check on Another Browser

Before you go for other solutions clear the cache of your browser and open a post in your WordPress Block Editor. If the issue is not fixed, login to your WordPress Admin section on another browser that you don’t use normally and open a post in your WordPress Block Editor.

When you update site settings, cache settings, plugin settings, or CDN settings, the new changes may not be updated on your browser, as a result your site or its features do not function properly. By clearing the cache you remove the cached data of your browser, that also includes error pages.

Go through this tutorial to learn about how to clear the cache of different browsers.

  • How To Clear History, Cookies, Cache In Chrome, Firefox, Opera And Microsoft Edge

Clear your browser cache

02. Enable Cache All Query Strings on CDN Settings

One of the primary causes of The Rest API did not behave correctly is your CDN settings. You have not enabled Cache All Query Strings option, rather you have enabled Ignore Query Strings option that ignores the query strings of URLs.

A query string is a part of URL that assigns a values to parameters. It appear after the Question Mark (?) in the URL. For example, “https://example.com/wp-admin/post.php?post=25416&action=edit”.

When you enable Cache All Query Strings option on your CDN settings, it can reduce cache duplication and optimize cache storage.

Here, I am guiding you on how to enable Cache All Query Strings option on Namecheap Supersonic CDN settings. If your site is linked with other CDNs such as Cloudflare, StackPath, etc, you can find the relevant option there.

  • Login to your Namecheap account.
  • Go to Apps from the sidebar and click on the Supersonic CDN.

Go to Apps from the sidebar and click on the Supersonic CDN.

  • Click on the Login with Namecheap button.

Click on the Login with Namecheap button.

  • Click on the Manage button.

Click on the Manage button.

  • Click on the CDN Settings from the sidebar.

Click on the CDN Settings.

  • Go to Query String Control section.
  • Select Cache All Query Strings option and Update/Save the changes.

Now clear the cache of your browser, login to your WordPress Admin section, and open a post on Block Editor. The layout of Block Editor should be fixed. If doesn’t fix, try checking on another browser.

Go to Query String Control section. Select Cache All Query Strings option and Update/Save the changes.

03. Disable REST API Features on Yoast Plugin

The Rest API did not behave correctly issue can also be occurred due to Yoast SEO plugin’s site feature REST API endpoint. Disabling this feature may remove the issue from your WordPress site.

  • Go to Yoast SEO from the sidebar.
  • Click on the Settings.

Go to Yoast SEO from the sidebar. Click on the Settings.

  • Click on the Site features from the sidebar.

Click on the Site features from the sidebar.

  • Scroll-down to APIs section and disable the REST API endpoint feature.

Scroll-down to APIs section and disable the REST API endpoint feature.

  • Click on the Save Changes button.

Login to your WordPress Admin section, and open a post on Block Editor to check whether the issue is fixed or not.

Click on the Save Changes button.

04. Other Solutions

If the above solutions don’t work you can try these solutions:

  1. Disable Your Plugins: The REST API error can also be caused by your WordPress plugins and active theme. You can disable all the plugins and enable them one-by-one to identify which one is causing the issue. If you don’t want to do this manually you can use the plugin Health Check & Troubleshooting. It disables all your plugins and uses a default theme without affecting your live site, as it does only for you.
  2. Check the Settings of Security Plugins: Some security-centric WordPress plugins such as Wordfence Security, WP Hide & Security Enhancer, Disable REST API, Titan Anti-spam & Security, WP Cerber Security, and NinjaFirewall have the ability to disable/block/restrict REST API. If any of the plugin is installed, you can check its settings.
  3. Pause your CDN: Pause your CDN temporary to check whether it is causing the issue. Your CDN can block the REST API. Its firewall can inadvertently block legitimate requests. You can check the Rule Set to confirm if the REST API is being blocked. You can remove/disable such rules and allow REST API to communicate with your site. After pausing the CDN or updating the Rule Set don’t forget to clear the cache of your browser.
  4. Enable Debug Mode: You can enable the WordPress Debug Mode to troubleshoot the REST API issue. The errors are stored in a debug.log file in the WP-content directory. You can search the debug.log file to find the errors which are blocking the REST API.

The Debug Mode in WordPress can be enabled by adding the below code in the wp-config.php file. After issue is resolved, remove this code from the wp-config.php file.

define( 'WP_DEBUG', true );  // Enables WP_DEBUG mode
define( 'WP_DEBUG_LOG', true ); 

I hope that my recommended solutions would have helped you to fix the issue, The REST API did not behave correctly. If you like this post, then don’t forget to share with other people. Share your feedback in the comments section below.

Download Website themes

Also Read

  • Fixed: Update Failed Could Not Update Post in the Database
  • 403 Forbidden Access to this Resource on the Server is Denied!
  • Fixed: Updating failed. The response is not a valid JSON response
  • How to Remove Lazy Loading on Featured Image in WordPress
  • How to Enable Persistent Object Cache on WordPress
  • How to Fix Your Sitemap Appears to be an HTML Page | GSC

Meer Basit

Meer Basit is the founder of Meer’s World. He’s been running the show since launching the blog back in 2018. By background he is a computer scientist. Primarily, he creates content around blogging (WordPress, Blogger, Tumblr), SEO, affiliate programs, earn-online, & eCommerce. He has got years of professional experience in web programming, computer programming, & databases. In general, he likes traveling, gardening, watching movies, is a passionate cricketer, creative writer, and a GSD lover.

Понравилась статья? Поделить с друзьями:
  • Register filter driver exception ошибка
  • Rest api выдал ошибку wordpress
  • Remote access 20063 ошибка
  • Resident evil 5 re5dx9 exe неустранимая ошибка приложения
  • Regedit ошибка файловой системы