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.
If you only see a loading animation, but the actual content in one of our plugins does not load, your WordPress REST API is most likely not reachable.
What is the WordPress REST API?
A REST API is generally a standardized method that many applications on the Internet use to communicate between server and client. WordPress v4.7 introduced the WordPress REST API, which allows modern WordPress plugins to use this standard method for communication instead of the WordPress specific way of communication.
How can I enable the WordPress REST API in my website?
The WordPress REST API is enabled by default in your WordPress website. It is a standard method of communication and there is no additional risk to have it activated compared to other methods how WordPress plugins communicate between client and server. But some WordPress plugins allow you as WordPress admin to disable the REST API. The reason for deactivation is usually the desire for better performance or security concerns. For both aspects, however, disabling the REST API is usually not a suitable means.
We know the following plugins that allow you to disable the REST API. By default, none of these plugins disable the REST API, but they can optionally disable it:
- Wordfence
- iThemes Security (formerly Better WP Security)
- All In One WP Security & Firewall
- Sucuri Security
- Titan Anti-spam & Security
- Cerber Security, Anti-spam & Malware Scan
- Shield Security
- WP Hide & Security Enhancer
- BulletProof Security
- Disable REST API
- NinjaFirewall (WP Edition)
- Hide My WP Ghost
- Perfmatters
- Swift Performance
- Clearfy
- WP Oath Server
- Password Protected
- Cloudflare WAF (Web Application Firewall)
- WP REST API Controller
Additionally, you can restrict access to the REST API in your web server configuration (usually Apache2 or NGINX). This can be done intentionally or accidentally by rejecting requests that start with /wp-json/
.
How do I know if the unreachable REST API is my issue?
You can easily check if an unreachable REST API is the problem when you see only a loading animation in a devowl.io WordPress plugin. Just follow these steps:
- Open a new tab where you access your website.
- Right-click into the web page to open the panel “Inspect” (Google Chrome) or “Inspect Element” (Mozilla Firefox). Here you can go to the “Console” tab.
- Now open the page on which you see the loading animation that does not disappear.
- In the console, you should see an entry marked red as an error, which indicates an error 401, 403, 404 or 500 (depending on your plugin/configuration to disable the REST API).
If you see an error like this, you need to make sure that the WordPress REST API is reachable again.
I do not want to enable the REST API in general, but for your plugin. Is this possible?
This depends on the configuration of the plugin you use to restrict access to the REST API. For example, with Cerber Security, Anti-spam & Malware Scan you can disable the REST API using namespaces. Each plugin that uses the WordPress REST API must register a namespace in which all endpoints are registered. For example, if you access /wp-json/realmedialibrary/v1
in your WordPress REST API, the namespace is called realmedialibrary/v1
.
We use for the devowl.io WordPress plugins the following namespaces:
- Real Media Library:
realmedialibrary/v1
- Real Physical Media:
real-physical-media/v1
- Real Category Management:
real-category-library/v1
- Real Thumbnail Generator:
real-thumbnail-generator/v1
- Real Custom Post Order:
real-custom-post-order/v1
- Real Cookie Banner:
real-cookie-banner/v1
(must be available for everyone, not only for logged-in users)
Besides WordPress plugins, we also use third-party packages that are consumed by our plugins. For this, you still have to release the following name ranges:
- Real Product Manager (license and update client, all plugins):
real-product-manager-wp-client/v1
- Real Queue (queue management, currently only used in Real Cookie Banner):
real-queue/v1
I am using a plugin like “JWT Auth”. Is it compatible?
If you need to use a plugin like JWT Auth you also need to whitelist our plugins. In case of JWT Auth, you have to read the section “Whitelisting Endpoints” in its README file and add our plugins to the allowed endpoints. The endpoints can be found in the paragraph above.
I don’t use a plugin, but e.g. NGINX to block the REST API
If you use a server configuration, e.g. the .htaccess
file or a NGINX configuration to block access to wp-json
, you should exclude certain subpaths. You can track these in the Network tab of your develeper tools in the browser and unblock them accordingly.
Some of our plugins also use a mechanism to obfuscate URLs to bypass ad blockers (for example, saving consent in Real Cookie banners). This can for example look like this: /wp-json/jr5ek52mpe4hqt2dhfu/mrvekpi0/0ed0fef9da/consent
. Unlike plugins that block the REST API, a server configuration that blocks the REST API must also unblock the path of the obfuscated URL. The obfuscation can be disabled through the DevOwl/Utils/RestObfuscatePath filter.
Permalinks are broken
If you use Apache2 as web server, the .htaccess
file defines how URLs of your website look like. This file is created automatically and sometimes manipulated by plugins. If something went wrong with the creation, this can also be a reason why the WP REST API can no longer be accessible.
So, you can rewrite the rules in the .htaccess
file:
- Go to Settings > Permalinks in your WordPress backend.
- Save the unchanged settings. Saving will trigger the rules to be rewritten.
I can read data but not write?
You are using Real Cookie Banner and cannot save your licence or create folders in Real Media Library? A typical error message text is:
Missing parameter(s): terms (or similar field names)
The most commonly identified cause of this behaviour with previous clients was that your server is configured to forward URLs without an ending slash /
to URLs with an ending slash /
(or vice versa).
You can track this by checking the respective requests via F12 > Network to see if a POST
request is redirected. A POST
request must not be redirected and therefore leads to errors, as data to be saved (your input) is not redirected.
It is best to check your .htaccess
file to see if you can exclude /wp-json
from URL forwarding.
See also: https://docs.wp-rocket.me/article/131-redirection-to-enforce-trailing-slash-on-urls
Skip to content
-
Hello,
I installed the Site Health Tool and got this message:
The Rest API encountered an error
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.
When testing the REST API, an error was encountered:
REST API Endpoint: https://mydomain.com/wp-json/wp/v2/types/post?context=edit
REST API Response: (http_request_failed) cURL error 28: Operation timed out after 10015 milliseconds with 0 bytes received
I deactivated while troubleshooting all the plugins and turned on a standard theme (twenty-twenty), but the problem still persists.
Help or a hint, where to find help, greatly appreciated.
Thanks,
miednr
- The topic ‘Critical issue: The Rest API encountered an error’ is closed to new replies.
Ошибка REST API стала головной болью для большинства владельцев сайтов на WordPress с того момента, как в панели управления (панели администратора) появился раздел «Здоровье сайта». Тревожное сообщение — «Запрос к REST API неудачен из-за ошибки» — не поддавалось разгадке без специальных знаний в области разработки на PHP. Учитывая, что среди пользователей WordPress программистов чуть больше одной десятой процента, проблема стала актуальной для миллионов менее чем за год.
Решение я нашёл самостоятельно и, без сложных объяснений, сразу перейду к нему.
Ошибка в теме сайта
Способ может показаться слишком простым, но достаточно переключиться на одну из новых стандартных тем WordPress, как сообщение об ошибке REST API исчезает. Возвращаемся к старому дизайну — ошибка возвращается.
Точно также происходит и с другой распространённой проблемой, которая называется «ваш сайт не смог выполнить петлевой запрос». Если в разделе «Здоровье сайта» система сообщает, что «петлевой запрос к вашему сайту не удался. Возможности, зависящие от его работоспособности, не могут работать так, как должны» — знайте, что пришло время менять тему вашего сайта.
Что делать
Самое действенное решение — установить более современный темплейт. Быстро и радикально, но не всегда подходит. Особенно, если сайту десяток лет, он выстрадан, сбалансирован и его любят посетители. Для таких проектов резкие движения противопоказаны. В этом случае, выбираем более трудоёмкий путь.
Вам нужен прилежный верстальщик, а лучше в паре с талантливым дизайнером, а ещё лучше чтобы с ними рядом трудился над вашим проектом разработчик на PHP. Пара недель (или месяцев) страданий, пара сотен (или тысяч) долларов — и ваш сайт снова молод, свеж и пахуч.
Примечание: сайт, который вы сейчас видите, читая этот текст, работает в паре со стандартной темой «Twenty Fifteen». В данный момент, версия темы — 2.5, но ни сейчас, ни на одной из прежних версий «Fifteen» я ни разу не получал уведомлений об ошибках REST API или петлевых запросов.
Для тех, кто владеет английским языком — документ в формате Portable Document Format (PDF), с полным описанием архитектурного стиля разработки REST и его стандартов.
The WordPress REST API is the best way to access or modify WordPress data asynchronously without slowing down your site or your admin. You can expect the whole WordPress admin to use it someday (and you will love it when it is).
If you are worried about the security of the REST API, check the end of this article.
If you get an error related to the REST API, it might be two things : it’s either that the WordPress REST API is not enabled, or that the asynchronous request to the REST API was either rejected or failed.
This article will be improved based on your experience. Please don’t hesitate to share your issues and solutions in the comments. Thank you! ☺️
Is the WordPress REST API enabled?
The best way to check is to visit this URL: https://yoursite.com/wp-json. If you see some information which seems related to your WordPress REST API, it works. If you see something, it means that, at least, your WordPress REST API is enabled. Otherwise, that’s not working, and you will need to understand why.
If you are using one of my plugins (Meow Apps), don’t expect to see any information about it. My plugins only load their code when they are being used, for optimization purposes (and let’s say, additional security too!).
Enable Permalinks
Visit your Settings > Permalinks. Make sure Plain is not selected. Usually, Post Name is the best choice. Even if everything is fine, click on Save Changes. That will rewrite/repair your .htaccess.
Security Plugins
They might block the REST API. Make sure it doesn’t, by disabling it temporarily. Known plugins to cause issues are:
- WP Cerber Security
- WPS Bidouille
- Plugin Organizer
Services like Cloudflare don’t cause any issues.
Caching Plugins
Many of my users had an issue with W3 Total Cache. If you use it, try to to clear your Object Cache in the Settings. Also, avoid caching anything related to the REST API; the requests to it aren’t meant to be cached, most of the time.
Modified .htaccess
It is possible that you or your system administrator modified the .htaccess to add a Content Security Policy. I have to admit, I am not very acquainted with this, but please be aware that customized .htaccess can actually restrict many requests to your site. Make sure it doesn’t.
Check your code
Certain lines of code can be written to disable the REST API. If you find those, simply delete them.
add_filter('rest_enabled', '_return_false');
add_filter('rest_jsonp_enabled', '_return_false');
The REST API is enabled, but it breaks (broken reply)
It means that either an error has happened on the server side, or that the server rejected that request.
- To knows if it’s an error, check this: The PHP Error Logs.
- To know if it’s a network/server issue (rejected or timed out request), check this: Check Network Activity with Google Chrome. It’s usually a good idea to talk with your hosting service in this case, as the might be able to help you and share with you more information.
Keep in mind that the error might be directly related to the plugin you are having a problem with. Any other plugin can interfere and break the request.
Is the WordPress REST API secure?
Like any software, it can’t be perfect. But generally, it is very secure, and constantly checked by security professionals for new vulnerabilities. In fact, when plugins (or new WordPress features) are built, developers have the choice of using the REST API or implement their own way to access the data. And you guessed it, the latter it much less secure.
Basically, do you prefer to have one hundred slightly hidden doors to access your house, or one big and obvious metal door covered with security cameras and alarm systems on it? Enable the REST API, make sure developers are using it to create new features, and believe me, you will sleep better at night 🙂