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:8472nStack 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 программистов чуть больше одной десятой процента, проблема стала актуальной для миллионов менее чем за год.
Решение я нашёл самостоятельно и, без сложных объяснений, сразу перейду к нему.
Ошибка в теме сайта
Способ может показаться слишком простым, но достаточно переключиться на одну из новых стандартных тем WordPress, как сообщение об ошибке REST API исчезает. Возвращаемся к старому дизайну — ошибка возвращается.
Точно также происходит и с другой распространённой проблемой, которая называется «ваш сайт не смог выполнить петлевой запрос». Если в разделе «Здоровье сайта» система сообщает, что «петлевой запрос к вашему сайту не удался. Возможности, зависящие от его работоспособности, не могут работать так, как должны» — знайте, что пришло время менять тему вашего сайта.
Что делать
Самое действенное решение — установить более современный темплейт. Быстро и радикально, но не всегда подходит. Особенно, если сайту десяток лет, он выстрадан, сбалансирован и его любят посетители. Для таких проектов резкие движения противопоказаны. В этом случае, выбираем более трудоёмкий путь.
Вам нужен прилежный верстальщик, а лучше в паре с талантливым дизайнером, а ещё лучше чтобы с ними рядом трудился над вашим проектом разработчик на PHP. Пара недель (или месяцев) страданий, пара сотен (или тысяч) долларов — и ваш сайт снова молод, свеж и пахуч.
Примечание: сайт, который вы сейчас видите, читая этот текст, работает в паре со стандартной темой «Twenty Fifteen». В данный момент, версия темы — 2.5, но ни сейчас, ни на одной из прежних версий «Fifteen» я ни разу не получал уведомлений об ошибках REST API или петлевых запросов.
Для тех, кто владеет английским языком — документ в формате Portable Document Format (PDF), с полным описанием архитектурного стиля разработки REST и его стандартов.
Здравствуйте.
настраиваю сайт, и возникло в процессе 2 критических ошибки.
Искала на форуме ответы, пока ничего из рекомендаций не помогло.
ОШИБКИ:
ОШИБКА 1 ТЕКСТ: REST API выдал ошибку
REST API это способ коммуникации между самим WordPress и другими приложениями. К примеру, экран редактора блоков использует его для отображения и сохранения ваших записей и страниц.
Запрос к REST API неудачен из-за ошибки.
Ошибка: [] cURL error 28: Connection timed out after 10001 milliseconds
ОШИБКА 2 ТЕКСТ: Ваш сайт не смог выполнить петлевой запрос.
Петлевые запросы используются для запуска запланированных заданий, а также используются встроенным редактором кода плагинов и тем для проверки корректности кода.
Петлевой запрос к вашему сайту не удался, возможности, зависящие от его работоспособности сейчас не работают как нужно.
Возникла ошибка: (0) cURL error 28: Connection timed out after 10001 milliseconds
! главное что попробовала пунктом 7 — это переустановка сайта, тестовой версии, ошибка появилась сразу же после установки базового пакета wordpress-5.5.3-ru_RU
написала хостеру, сказали что вопрос все таки с их стороны и будут разбираться.
Жду )
ЧТО ПРОБОВАЛА ДЕЛАТЬ:
1. отключала полностью все плагины — эти 2 ошибки остались
2. отключала свою тему, заменяла на стандартную «Twenty twenty» — эти 2 ошибки остались
3. php изначальностояла 7.4. меняла версии php , из на меньшую 5.6. и на большую 7.3 — эти 2 ошибки остались
4. пробовала делать отладку с помощью Health Check & Troubleshooting — эти 2 ошибки остались
5. Обращалась к хостеру в службу поддержки — с их стороны (со стороны сервера) ошибок нет. cURL — enabled и другие показатели тоже в норме.
6. с настройкой https — тоже вроде как все работает в порядке.
.7. — написала выше.
Что еще можно сделать для устранения этих 2-х ошибок?
-
Тема изменена 2 года, 6 месяцев назад пользователем
boreaesy. Причина: новая информация
В связи с появлением свободного времени, решил Я проверить техническое состояние своего сайта, произвести обновление различных компонентов (WordPress, PHP, MySQl, Apache и т.д) и проверить работоспособность программного обеспечения. Открыв «Здоровье сайта» если кто не знает это встроенный инструмент для диагностики состояния системы и сервера, я увидел сообщение о двух критических проблемах «Обнаружена активная PHP сессия» и «REST API выдал ошибку». Когда появились эти ошибки было не понятно, но думаю достаточно давно так как данный инструмент последний раз Я открывал наверно еще в прошлом году. Влияние этих ошибок на работоспособность сайта было совсем не значительное, так как сайт работал в штатном режиме. Но раз проблемы есть да и еще критические их хотелось решить. Поискав информацию в интернете, Я понял что в большинстве случаем причины появления этих ошибка практически одинаковые, и решение одно и тоже. Сегодня хочу поделиться своим случаем.
И так вы обнаружили следующие критические проблемы на своем сайте.
Обнаружена активная 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
boreaesy. Причина: новая информация