Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Copa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Como desativar a API REST JSON no WordPress

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Recentemente, um de nossos leitores nos perguntou: como faço para desativar a API REST em meu site do WordPress?

Quando a versão 4.4 do WordPress foi lançada, ela veio com a tão esperada API JSON REST. Embora seja excelente para os desenvolvedores de plug-ins, muitos proprietários de sites talvez não a considerem útil.

Neste artigo, mostraremos como desativar facilmente a API JSON REST no WordPress.

Disable JSON REST API in WordPress

Por que desativar a API REST JSON no WordPress?

Não há como negar que a API traz muitos benefícios para os desenvolvedores do WordPress. A API facilita muito a recuperação de dados usando solicitações GET, o que é útil para quem está criando aplicativos com o WordPress.

Dito isso, é possível que isso abra seu site para uma nova frente de ataques DDoS. Também pode consumir muitos recursos e tornar seu site WordPress mais lento.

Desativar a API REST JSON é semelhante a desativar o XML-RPC, que muitos administradores de sites desativam em seus sites WordPress apenas por segurança.

Mostraremos a você dois métodos para desativar facilmente a API JSON REST no WordPress. Basta usar os links rápidos abaixo para ir para o método que você deseja usar.

Método 1. Desativação da API REST JSON no WordPress com código (recomendado)

Recomendamos usar o plug-in WPCode para desativar a API REST JSON no WordPress.

WPCode

O WPCode torna seguro e fácil adicionar códigos personalizados no WordPress, sem editar o arquivo functions.php do seu tema. Dessa forma, não há risco de cometer um erro e danificar seu site.

Além disso, ele vem com uma biblioteca de código integrada que inclui trechos de código verificados para solicitações de recursos populares, como desativar a API REST, desativar o XML-RPC e muito mais. Isso evita que você tenha que instalar vários plug-ins de uso único.

Para começar, você precisa instalar e ativar o plug-in gratuito WPCode. Para obter instruções passo a passo, leia nosso guia sobre como instalar um plug-in do WordPress.

Observação: a versão gratuita do WPCode tem tudo o que você precisa para adicionar facilmente códigos personalizados no WordPress. Mas, se você quiser recursos avançados, como uma biblioteca de snippets em nuvem privada, snippets específicos para páginas e dispositivos, revisões de código e muito mais, poderá fazer upgrade para o WPCode Pro.

Depois que o plug-in for ativado, acesse Code Snippets ” Library no painel do WordPress.

Em seguida, procure o snippet “Disable WordPress REST API” (Desativar API REST do WordPress) e clique no botão “Use snippet” (Usar snippet).

Select the Disable WordPress REST API in WPCode

O plug-in adicionará automaticamente o código e selecionará o método de inserção adequado.

WPCode automatically adds the Disable JSON REST API snippet

Tudo o que você precisa fazer é alternar a chave de “Inativo” para “Ativo”.

Em seguida, clique no botão “Update” (Atualizar).

Switch the code snippet to Active and click Update in WPCode

É isso aí. Agora a API REST JSON está desativada em seu site WordPress.

Método 2. Como desativar a API REST JSON no WordPress com um plug-in

A primeira coisa que você precisa fazer é instalar e ativar o plug-in Disable REST API. Para obter mais detalhes, consulte nosso guia passo a passo sobre como instalar um plug-in do WordPress.

O plug-in funciona imediatamente e não há configurações a serem definidas.

Agora, ele retornará forçosamente um erro de autenticação para qualquer solicitação de API de fontes que não estejam conectadas ao seu site.

Isso impedirá efetivamente que solicitações não autorizadas usem a API REST para obter informações de seu site.

Você pode testar isso visitando a página http://example.com/wp-json. Certifique-se de fazer logout da área de administração do WordPress primeiro ou mude seu navegador para o modo de navegação anônima.

Não se esqueça de substituir example.com por seu próprio nome de domínio. Você verá esta mensagem, indicando que as solicitações da API REST estão bloqueadas.

REST API Disabled

Isso é tudo, você desativou com êxito as solicitações não autorizadas da API REST em seu site do WordPress.

Esperamos que este artigo tenha ajudado você a aprender como desativar a API JSON no WordPress. Os usuários preocupados com a segurança também podem querer conferir estas dicas sobre como proteger a área de administração do WordPress ou ver nossas escolhas esperadas dos melhores plug-ins de backup do WordPress.

Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

37 ComentáriosDeixe uma resposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

    • WPBeginner Support says

      If you have many different plugins and tools and have a testing environment then it would definitely be good to test new plugins and how they interact with your site.

      Administrador

  2. Ricky says

    Similar to an above commenter, I’ve noticed the “wp-json” request when using Pingdom and other testing sites. Unfortunately, mine takes over 10 seconds (Yes really!!) to load it. This pushes my overall website load time and I can’t figure out how to fix this. The plugin doesn’t change it at all. Any suggestions?

  3. Janice says

    How do I know if I actually have JSON API on my website?
    This article about removing it is good – if I need it – but I have often been alarmed by certain warnings only to find that they’ve not even applicable to me.

  4. Logan Cale says

    I hate adding yet another plugin to do a simple tasks, and I found that we can disable this functionality by adding the following code snippet to the functions.php file.

    add_filter(‘rest_enabled’, ‘_return_false’);
    add_filter(‘rest_jsonp_enabled’, ‘_return_false’);

  5. J.L. says

    Is this just for self hosted blogs or including free blog sites? Per mostly all plug ins…etc are done for you when you’re not self hosted

    PS I’m not subscribing…just want a response

  6. Elaine says

    How can I check if my site has Rest API. I turned off a lot of extras when I first set it up but now don’t know where to look to see if it’s there. Not keen to download a plugin unnecessarily.

    • WPBeginner Support says

      Hey Elaine,

      You can check if rest is api is enabled on your site by visiting the url like this example.com/wp-json. Make sure you are signed out of WordPress before doing that. If you see lots of information in plain text, then this means REST API is enabled on your site. Follow the above instructions to turn it off

      Administrador

  7. Ken Dowling says

    Is disabling REST API suitable for e-commerce sites such as WooCommerce? My understanding is that WooCommerce uses REST-API quite a bit.

    Further, my buyers do not have to login to buy, so what happens to the transaction when a REST API call is rejected?

    Regards, Ken

  8. D. Joe Chaffin says

    Plug-in makes no difference for me in WP 4.7.2. With the plugin activated or disabled, the example.com/wp-json (with my domain replacing “example”) pages gives a massive list of settings for my site.

    • D. Joe Chaffin says

      Hmmmm. Now that I look at it, I only see the list in Safari, while Chrome and Firefox for Mac show the expected message specified in this post.

    • WPBeginner Support says

      Hi,

      Make sure you are logged out of WordPress admin area or use incognito mode before testing the example.com/wp-json page. The plugin disables access to the page only for unauthorized users. As an administrator you will still be able to see it.

      Administrador

  9. Audra Carpenter says

    Hey Guys,

    First off thanks so much for what you do! I’ve learned so much about WordPress from you and sent a ton of folks your way!!

    Ok, I installed the plugin, but I am not seeing what you suggest above? I have a full screen of information…?

    Thoughts?

    Thanks!

  10. Treasure says

    I followed these steps, but when I went to check it with the example etc., I got 2 pages of code, not the response showed above. Hmmm, don’t know what to do.

  11. Doug Nix says

    When I ran the test I think it failed, as I got a boatload of data on screen. Any idea what might have not worked? I installed the plugin as described…

    • Doug Nix says

      Works perfectly when I check using an incognito window. Thanks for the explanation regarding authorised vs unauthorised or anonymous users.

  12. Karl says

    Thanks for the tip as well as for the hook to disable XMLRPC.
    Is there a chance for a filter hook for the REST API as well?

  13. Andrew says

    When I check the speed of my site using pingdom.com, the first html entry that tried to load shows the link as mydomain.com/wp-json and it has over 2 seconds of “wait” time. Is this the same as what this article is talking about? I’m hesitant to simply disable it since I would assume it will be used in the future. Any idea why it would add a 2+ second delay to loading anything on the page?

  14. Stephen Cronin says

    Hmm, the REST API is going to become the standard way for plugins and themes to make Ajax calls back to the server from the front end, replacing admin-ajax, so I wouldn’t be disabling it… Hopefully they will fail gracefully, but you will almost end up missing some functionality.

    Also, if you really want to protect against DDoS attacks, you better disable html as well! ;)

    • reza says

      ver 50,000 WordPress websites have been hacked due to a major security vulnerability that was discovered in the WordPress REST API.

      • Jim S Smith says

        OUCH!

        That’s disturbing to know. I have noticed a LOT of access attempts in my site’s logs.

        What’s more,

        I think the folks at WordPress could have done a little better in letting the users decide how much, if at all, they want the REST API exposed.

        Again,

        More of this, “The developers know MORE about the user’s needs than the user does!” – I also was not too happy about being forced to support EMOJI and remote-loaded fonts from fonts.google.com, even though my sites do not use them!

        The REST API may be a boon for (some) actual web-application developers, but what about the rest of us who will not very likely use this? ? ?

  15. Kasey says

    How likely is it that a plugin will be using this functionality. Just for example would contact forms be utilizing this? Not keen on turning it off in case it breaks anything.

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.