{"id":1973,"date":"2024-10-09T11:37:53","date_gmt":"2024-10-09T03:37:53","guid":{"rendered":"https:\/\/www.openbyt.com\/persuasion-is-often-more-effectual-than-force-2"},"modified":"2024-10-17T19:56:16","modified_gmt":"2024-10-17T11:56:16","slug":"persuasion-is-often-more-effectual-than-force-2","status":"publish","type":"post","link":"https:\/\/www.openbyt.com\/pt\/a-persuasao-e-frequentemente-mais-eficaz-do-que-a-forca-2","title":{"rendered":"Domine a API REST do WordPress: Autentica\u00e7\u00e3o e integra\u00e7\u00e3o"},"content":{"rendered":"<p><strong>O que \u00e9 a API REST?<\/strong><\/p><p><strong>API REST (Interface de Programa\u00e7\u00e3o de Aplica\u00e7\u00f5es de Transfer\u00eancia de Estado Representacional) <\/strong>\u00e9 um conjunto de regras que permite que diferentes sistemas de software comuniquem atrav\u00e9s da Internet. Imagine uma API como uma ponte que liga dois sistemas, permitindo-lhes pedir e partilhar informa\u00e7\u00f5es.<\/p><figure class=\"wp-block-image size-full\"><img fetchpriority=\"high\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.23.43-An-illustration-of-how-a-REST-API-works.-Include-a-visual-representation-of-an-API-as-a-bridge-connecting-two-systems-a-client-and-a-server-with-ar.webp\" alt=\"\" class=\"wp-image-2249\" srcset=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.23.43-An-illustration-of-how-a-REST-API-works.-Include-a-visual-representation-of-an-API-as-a-bridge-connecting-two-systems-a-client-and-a-server-with-ar.webp 1024w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.23.43-An-illustration-of-how-a-REST-API-works.-Include-a-visual-representation-of-an-API-as-a-bridge-connecting-two-systems-a-client-and-a-server-with-ar-600x600.webp 600w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.23.43-An-illustration-of-how-a-REST-API-works.-Include-a-visual-representation-of-an-API-as-a-bridge-connecting-two-systems-a-client-and-a-server-with-ar-100x100.webp 100w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.23.43-An-illustration-of-how-a-REST-API-works.-Include-a-visual-representation-of-an-API-as-a-bridge-connecting-two-systems-a-client-and-a-server-with-ar-300x300.webp 300w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.23.43-An-illustration-of-how-a-REST-API-works.-Include-a-visual-representation-of-an-API-as-a-bridge-connecting-two-systems-a-client-and-a-server-with-ar-150x150.webp 150w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.23.43-An-illustration-of-how-a-REST-API-works.-Include-a-visual-representation-of-an-API-as-a-bridge-connecting-two-systems-a-client-and-a-server-with-ar-768x768.webp 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><p>Vamos decompor os componentes de uma API REST:<\/p><ul class=\"wp-block-list\"><li><strong>API (Interface de Programa\u00e7\u00e3o de Aplica\u00e7\u00f5es)<\/strong>: Uma API \u00e9 como um menu num restaurante. Fornece uma lista de opera\u00e7\u00f5es que um cliente pode solicitar, e o servidor (como um chefe) executa essas opera\u00e7\u00f5es e devolve a resposta.<\/li>\n\n<li><strong>REST (Transfer\u00eancia de Estado Representacional)<\/strong>: REST \u00e9 um conjunto de diretrizes para a cria\u00e7\u00e3o de servi\u00e7os Web que funcionam atrav\u00e9s de HTTP, utilizando opera\u00e7\u00f5es padr\u00e3o como GET, POST, PUT e DELETE.<\/li><\/ul><figure class=\"wp-block-image size-full\"><img decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.26.03-An-illustration-depicting-an-API-as-a-menu-in-a-restaurant.-Show-a-client-customer-selecting-from-a-menu-of-operations-with-a-server-chef-perform.webp\" alt=\"\" class=\"wp-image-2251\" srcset=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.26.03-An-illustration-depicting-an-API-as-a-menu-in-a-restaurant.-Show-a-client-customer-selecting-from-a-menu-of-operations-with-a-server-chef-perform.webp 1024w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.26.03-An-illustration-depicting-an-API-as-a-menu-in-a-restaurant.-Show-a-client-customer-selecting-from-a-menu-of-operations-with-a-server-chef-perform-600x600.webp 600w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.26.03-An-illustration-depicting-an-API-as-a-menu-in-a-restaurant.-Show-a-client-customer-selecting-from-a-menu-of-operations-with-a-server-chef-perform-100x100.webp 100w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.26.03-An-illustration-depicting-an-API-as-a-menu-in-a-restaurant.-Show-a-client-customer-selecting-from-a-menu-of-operations-with-a-server-chef-perform-300x300.webp 300w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.26.03-An-illustration-depicting-an-API-as-a-menu-in-a-restaurant.-Show-a-client-customer-selecting-from-a-menu-of-operations-with-a-server-chef-perform-150x150.webp 150w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.26.03-An-illustration-depicting-an-API-as-a-menu-in-a-restaurant.-Show-a-client-customer-selecting-from-a-menu-of-operations-with-a-server-chef-perform-768x768.webp 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><p><strong _msttexthash=\"32972290\" _msthash=\"186\">Como \u00e9 que uma API REST funciona?<\/strong><\/p><p>A API REST permite que os clientes (como o seu browser ou uma aplica\u00e7\u00e3o) enviem pedidos aos servidores e recebam dados em troca. Vamos explicar-lhe como funciona, passo a passo:<\/p><ol class=\"wp-block-list\"><li><strong>Pedido do cliente<\/strong>: O cliente (a sua aplica\u00e7\u00e3o) envia um pedido HTTP para um URL espec\u00edfico no servidor. Este URL representa um recurso (por exemplo, um utilizador, um produto, etc.).<ul class=\"wp-block-list\"><li>Exemplo: GET <code>https:\/\/api.example.com\/users<\/code> solicita a lista de utilizadores.<\/li><\/ul><\/li>\n\n<li><strong>Processamento do servidor<\/strong>: O servidor recebe o pedido, processa-o, recupera os dados (normalmente de uma base de dados) e prepara uma resposta.<\/li>\n\n<li><strong>Resposta do servidor<\/strong>: O servidor envia uma resposta HTTP de volta ao cliente. Esta resposta inclui:<ul class=\"wp-block-list\"><li><strong>C\u00f3digo de estado<\/strong>: Para indicar se o pedido foi bem sucedido (por exemplo, 200 OK para sucesso, 404 Not Found se o recurso n\u00e3o existir).<\/li>\n\n<li><strong>Dados<\/strong>: Normalmente em formato JSON, representa o recurso solicitado.<\/li><\/ul><\/li><\/ol><figure class=\"wp-block-image size-full\"><img decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.28.59-An-illustration-showing-the-process-of-a-client-sending-a-request-to-a-server.-Include-visuals-for-Client-Request-with-an-arrow-pointing-to-a-Serve.webp\" alt=\"\" class=\"wp-image-2252\" srcset=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.28.59-An-illustration-showing-the-process-of-a-client-sending-a-request-to-a-server.-Include-visuals-for-Client-Request-with-an-arrow-pointing-to-a-Serve.webp 1024w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.28.59-An-illustration-showing-the-process-of-a-client-sending-a-request-to-a-server.-Include-visuals-for-Client-Request-with-an-arrow-pointing-to-a-Serve-600x600.webp 600w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.28.59-An-illustration-showing-the-process-of-a-client-sending-a-request-to-a-server.-Include-visuals-for-Client-Request-with-an-arrow-pointing-to-a-Serve-100x100.webp 100w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.28.59-An-illustration-showing-the-process-of-a-client-sending-a-request-to-a-server.-Include-visuals-for-Client-Request-with-an-arrow-pointing-to-a-Serve-300x300.webp 300w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.28.59-An-illustration-showing-the-process-of-a-client-sending-a-request-to-a-server.-Include-visuals-for-Client-Request-with-an-arrow-pointing-to-a-Serve-150x150.webp 150w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.28.59-An-illustration-showing-the-process-of-a-client-sending-a-request-to-a-server.-Include-visuals-for-Client-Request-with-an-arrow-pointing-to-a-Serve-768x768.webp 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><p><strong>Autentica\u00e7\u00e3o b\u00e1sica:<\/strong> O que \u00e9 e porque \u00e9 que \u00e9 importante?<\/p><p><strong>Autentica\u00e7\u00e3o b\u00e1sica<\/strong> \u00e9 uma forma simples de os utilizadores verificarem a sua identidade quando solicitam uma API. Neste m\u00e9todo, o cliente envia o nome de utilizador e a palavra-passe codificados no cabe\u00e7alho do pedido, que o servidor valida.<\/p><p><strong>Porque \u00e9 que \u00e9 importante?<\/strong>: A autentica\u00e7\u00e3o garante que apenas os utilizadores autorizados t\u00eam acesso aos recursos, impedindo o acesso de utilizadores n\u00e3o autorizados.<\/p><p><strong>Como \u00e9 que funciona?<\/strong>: Quando um cliente envia um pedido ao servidor, inclui um <code>Autoriza\u00e7\u00e3o<\/code> com as credenciais codificadas em Base64.<\/p><p><strong>Exemplo\uff1a<\/strong><\/p><pre class=\"wp-block-code\"><code>Autoriza\u00e7\u00e3o: Basic dXNlcm5hbWU6cGFzc3dvcmQ=<\/code><\/pre><p>O servidor descodifica este cabe\u00e7alho e verifica se o nome de utilizador e a palavra-passe s\u00e3o v\u00e1lidos.<\/p><figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.34.10-An-illustration-explaining-Basic-Authentication-for-REST-API.-Show-a-simplified-visual-of-a-client-user-sending-an-HTTP-request-to-a-server-with-an.webp\" alt=\"\" class=\"wp-image-2255\" srcset=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.34.10-An-illustration-explaining-Basic-Authentication-for-REST-API.-Show-a-simplified-visual-of-a-client-user-sending-an-HTTP-request-to-a-server-with-an.webp 1024w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.34.10-An-illustration-explaining-Basic-Authentication-for-REST-API.-Show-a-simplified-visual-of-a-client-user-sending-an-HTTP-request-to-a-server-with-an-600x600.webp 600w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.34.10-An-illustration-explaining-Basic-Authentication-for-REST-API.-Show-a-simplified-visual-of-a-client-user-sending-an-HTTP-request-to-a-server-with-an-100x100.webp 100w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.34.10-An-illustration-explaining-Basic-Authentication-for-REST-API.-Show-a-simplified-visual-of-a-client-user-sending-an-HTTP-request-to-a-server-with-an-300x300.webp 300w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.34.10-An-illustration-explaining-Basic-Authentication-for-REST-API.-Show-a-simplified-visual-of-a-client-user-sending-an-HTTP-request-to-a-server-with-an-150x150.webp 150w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.34.10-An-illustration-explaining-Basic-Authentication-for-REST-API.-Show-a-simplified-visual-of-a-client-user-sending-an-HTTP-request-to-a-server-with-an-768x768.webp 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><p><strong>M\u00e9todos de autentica\u00e7\u00e3o para a API REST do WordPress<\/strong><\/p><p>Ao trabalhar com o <strong>API REST do WordPress<\/strong>Para proteger os pedidos, pode utilizar v\u00e1rios m\u00e9todos de autentica\u00e7\u00e3o:<\/p><p><strong>1\uff1aAutentica\u00e7\u00e3o b\u00e1sica<\/strong><\/p><ul class=\"wp-block-list\"><li>Este m\u00e9todo \u00e9 frequentemente utilizado para testes e aplica\u00e7\u00f5es simples. Envie o seu nome de utilizador e palavra-passe do WordPress nos cabe\u00e7alhos do pedido.<\/li>\n\n<li><strong>Dica de plug-in<\/strong>: Para utilizar a Autentica\u00e7\u00e3o B\u00e1sica com o WordPress, pode utilizar a op\u00e7\u00e3o <a href=\"https:\/\/github.com\/WP-API\/Basic-Auth\" target=\"_blank\" rel=\"noreferrer noopener\">Plug-in de autentica\u00e7\u00e3o b\u00e1sica<\/a>. Este m\u00e9todo n\u00e3o \u00e9 recomendado para ambientes de produ\u00e7\u00e3o devido a preocupa\u00e7\u00f5es de seguran\u00e7a.<\/li><\/ul><p><strong>2\uff1aAutentica\u00e7\u00e3o de cookies<\/strong><\/p><ul class=\"wp-block-list\"><li>A autentica\u00e7\u00e3o por cookie \u00e9 utilizada quando pretende que o utilizador com sess\u00e3o iniciada no momento aceda \u00e0 API. Quando um utilizador inicia sess\u00e3o no WordPress, \u00e9 criado um cookie de sess\u00e3o e a API utiliza este cookie para autenticar o utilizador.<\/li>\n\n<li><strong>Caso de utiliza\u00e7\u00e3o<\/strong>: Isto \u00e9 frequentemente utilizado para aplica\u00e7\u00f5es JavaScript front-end executadas no mesmo dom\u00ednio que o site WordPress.<\/li><\/ul><p><strong>3\uff1aAutentica\u00e7\u00e3o OAuth<\/strong><\/p><ul class=\"wp-block-list\"><li>O OAuth \u00e9 um m\u00e9todo mais seguro que permite que aplica\u00e7\u00f5es de terceiros acedam \u00e0 API REST do WordPress em nome dos utilizadores sem partilhar as suas palavras-passe.<\/li>\n\n<li><strong>Exemplo de plugin<\/strong>: Pode utilizar o Plugin de Servidor OAuth 1.0a para WordPress para implementar a autentica\u00e7\u00e3o baseada em OAuth.<\/li><\/ul><p><strong>4\uff1aSenhas de aplica\u00e7\u00f5es<\/strong><\/p><ul class=\"wp-block-list\"><li>O WordPress tamb\u00e9m suporta <strong>Palavras-passe de aplica\u00e7\u00f5es<\/strong>que s\u00e3o palavras-passe \u00fanicas para acesso \u00e0 API. Pode gerar palavras-passe de aplica\u00e7\u00e3o no seu painel de controlo do WordPress, e estas palavras-passe podem ser utilizadas para autentica\u00e7\u00e3o.<\/li>\n\n<li><strong>Como gerar<\/strong>: Aceda ao seu perfil de utilizador no WordPress, desloque-se para baixo at\u00e9 \u00e0 sec\u00e7\u00e3o \"Palavras-passe de aplica\u00e7\u00e3o\" e crie uma nova palavra-passe.<\/li><\/ul><figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.41.26-An-illustration-comparing-different-WordPress-REST-API-authentication-methods.-Include-visual-representations-for-Basic-Authentication-username-and-p.webp\" alt=\"\" class=\"wp-image-2257\" srcset=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.41.26-An-illustration-comparing-different-WordPress-REST-API-authentication-methods.-Include-visual-representations-for-Basic-Authentication-username-and-p.webp 1024w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.41.26-An-illustration-comparing-different-WordPress-REST-API-authentication-methods.-Include-visual-representations-for-Basic-Authentication-username-and-p-600x600.webp 600w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.41.26-An-illustration-comparing-different-WordPress-REST-API-authentication-methods.-Include-visual-representations-for-Basic-Authentication-username-and-p-100x100.webp 100w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.41.26-An-illustration-comparing-different-WordPress-REST-API-authentication-methods.-Include-visual-representations-for-Basic-Authentication-username-and-p-300x300.webp 300w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.41.26-An-illustration-comparing-different-WordPress-REST-API-authentication-methods.-Include-visual-representations-for-Basic-Authentication-username-and-p-150x150.webp 150w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.41.26-An-illustration-comparing-different-WordPress-REST-API-authentication-methods.-Include-visual-representations-for-Basic-Authentication-username-and-p-768x768.webp 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><p><strong>Maximizar o desenvolvimento com a API REST do WordPress<\/strong><\/p><p>A API REST do WordPress pode criar aplica\u00e7\u00f5es Web poderosas, permitindo-lhe interagir com o seu site WordPress a partir do exterior do painel de controlo do WordPress. Veja como pode maximizar o desenvolvimento:<\/p><p><strong>1\uff1aEndpoints personalizados:<\/strong> Pode criar pontos finais personalizados para expor dados adicionais do seu s\u00edtio WordPress que podem n\u00e3o estar dispon\u00edveis por predefini\u00e7\u00e3o.<\/p><ul class=\"wp-block-list\"><li><strong>Como criar<\/strong>: Utilize o bot\u00e3o <code>register_rest_route()<\/code> no seu tema ou plugin WordPress para adicionar novos pontos finais.<\/li><\/ul><p>Exemplo:<\/p><pre class=\"wp-block-code\"><code>add_action('rest_api_init', function() {\n  register_rest_route('myplugin\/v1', '\/custom-data\/', array(\n    'methods' =&gt; 'GET',\n    'callback' =&gt; 'my_custom_data_callback',\n  ));\n});\n\nFun\u00e7\u00e3o my_custom_data_callback() {\n  return new WP_REST_Response(array('data' =&gt; 'Hello, world!'), 200);\n}<\/code><\/pre><p><strong>2\uff1aIntegra\u00e7\u00e3o de JavaScript:<\/strong> Use JavaScript para enviar solicita\u00e7\u00f5es \u00e0 API REST para criar experi\u00eancias de usu\u00e1rio din\u00e2micas e interativas. Por exemplo, pode criar uma aplica\u00e7\u00e3o React ou Vue.js que interaja com o seu backend do WordPress atrav\u00e9s da API REST.<\/p><p><strong>Exemplo pr\u00e1tico<\/strong>: Imagine criar um sistema de coment\u00e1rios personalizado em que os utilizadores podem publicar coment\u00e1rios sem recarregar a p\u00e1gina, tudo atrav\u00e9s da intera\u00e7\u00e3o com a API REST via JavaScript.<\/p><figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.50.24-A-realistic-illustration-of-a-developer-working-on-WordPress-REST-API.-The-scene-includes-a-modern-workspace-with-a-developer-sitting-at-a-desk-in-fr.webp\" alt=\"\" class=\"wp-image-2258\" srcset=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.50.24-A-realistic-illustration-of-a-developer-working-on-WordPress-REST-API.-The-scene-includes-a-modern-workspace-with-a-developer-sitting-at-a-desk-in-fr.webp 1024w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.50.24-A-realistic-illustration-of-a-developer-working-on-WordPress-REST-API.-The-scene-includes-a-modern-workspace-with-a-developer-sitting-at-a-desk-in-fr-600x600.webp 600w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.50.24-A-realistic-illustration-of-a-developer-working-on-WordPress-REST-API.-The-scene-includes-a-modern-workspace-with-a-developer-sitting-at-a-desk-in-fr-100x100.webp 100w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.50.24-A-realistic-illustration-of-a-developer-working-on-WordPress-REST-API.-The-scene-includes-a-modern-workspace-with-a-developer-sitting-at-a-desk-in-fr-300x300.webp 300w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.50.24-A-realistic-illustration-of-a-developer-working-on-WordPress-REST-API.-The-scene-includes-a-modern-workspace-with-a-developer-sitting-at-a-desk-in-fr-150x150.webp 150w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.50.24-A-realistic-illustration-of-a-developer-working-on-WordPress-REST-API.-The-scene-includes-a-modern-workspace-with-a-developer-sitting-at-a-desk-in-fr-768x768.webp 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><p><strong>Enviando solicita\u00e7\u00f5es autenticadas com JavaScript<\/strong><\/p><p>Para enviar pedidos autenticados utilizando JavaScript, tem de incluir as credenciais ou tokens corretos nos cabe\u00e7alhos dos pedidos. Por exemplo:<\/p><pre class=\"wp-block-code\"><code>fetch('https:\/\/api.example.com\/users', {\n  m\u00e9todo: 'GET',\n  cabe\u00e7alhos: {\n    'Authorization': 'Basic ' + btoa('username:password'),\n    'Content-Type': 'application\/json'\n  }\n})\n  .then(response =&gt; response.json())\n  .then(data =&gt; console.log(data));<\/code><\/pre><p>Neste exemplo, a fun\u00e7\u00e3o btoa() codifica as credenciais em Base64 para autentica\u00e7\u00e3o prim\u00e1ria.<\/p><figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.54.03-An-illustration-showing-a-developer-using-JavaScript-to-send-authenticated-requests-to-a-REST-API.-Include-a-visual-of-a-computer-screen-with-JavaScri.webp\" alt=\"\" class=\"wp-image-2259\" srcset=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.54.03-An-illustration-showing-a-developer-using-JavaScript-to-send-authenticated-requests-to-a-REST-API.-Include-a-visual-of-a-computer-screen-with-JavaScri.webp 1024w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.54.03-An-illustration-showing-a-developer-using-JavaScript-to-send-authenticated-requests-to-a-REST-API.-Include-a-visual-of-a-computer-screen-with-JavaScri-600x600.webp 600w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.54.03-An-illustration-showing-a-developer-using-JavaScript-to-send-authenticated-requests-to-a-REST-API.-Include-a-visual-of-a-computer-screen-with-JavaScri-100x100.webp 100w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.54.03-An-illustration-showing-a-developer-using-JavaScript-to-send-authenticated-requests-to-a-REST-API.-Include-a-visual-of-a-computer-screen-with-JavaScri-300x300.webp 300w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.54.03-An-illustration-showing-a-developer-using-JavaScript-to-send-authenticated-requests-to-a-REST-API.-Include-a-visual-of-a-computer-screen-with-JavaScri-150x150.webp 150w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-16.54.03-An-illustration-showing-a-developer-using-JavaScript-to-send-authenticated-requests-to-a-REST-API.-Include-a-visual-of-a-computer-screen-with-JavaScri-768x768.webp 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><p><strong>Autentica\u00e7\u00e3o de cookies<\/strong><\/p><p>Ao trabalhar com autentica\u00e7\u00e3o de cookies, pode utilizar os cookies de sess\u00e3o do utilizador com sess\u00e3o iniciada no WordPress para aceder \u00e0 API REST. Veja aqui um exemplo passo a passo de como isso funciona:<\/p><ol class=\"wp-block-list\"><li><strong>O utilizador inicia sess\u00e3o<\/strong> O utilizador inicia sess\u00e3o no seu s\u00edtio WordPress e o WordPress define um cookie de autentica\u00e7\u00e3o no navegador do utilizador.<\/li>\n\n<li><strong>Enviar pedidos<\/strong>: Quando o seu c\u00f3digo JavaScript solicita a API REST, o browser inclui o cookie nos cabe\u00e7alhos do pedido e o WordPress sabe qual o utilizador que est\u00e1 a fazer o pedido.<\/li><\/ol><p><strong>Enviando solicita\u00e7\u00f5es com a API HTTP do WordPress<\/strong><\/p><p>Tamb\u00e9m pode utilizar o <strong>API HTTP do WordPress<\/strong> para enviar pedidos a partir do seu s\u00edtio WordPress. A API HTTP \u00e9 um conjunto de fun\u00e7\u00f5es que o WordPress fornece para interagir com as APIs REST.<\/p><p>Exemplo de envio de um pedido GET:<\/p><pre class=\"wp-block-code\"><code>$response = wp_remote_get('https:\/\/api.example.com\/users');\nSe (is_wp_error($response)) {\n  $error_message = $response-&gt;get_error_message();\n  echo \"Algo correu mal: $error_message\";\n} else {\n  $body = wp_remote_retrieve_body($response);\n  echo $body;\n}<\/code><\/pre><p>Este exemplo utiliza a fun\u00e7\u00e3o wp_remote_get() para enviar um pedido GET a uma API externa e obter a resposta.<\/p><h3 class=\"wp-block-heading\">Resumo<\/h3><p>Neste guia, abord\u00e1mos:<\/p><ul class=\"wp-block-list\"><li><strong>O que \u00e9 a API REST,<\/strong> e como \u00e9 que permite a comunica\u00e7\u00e3o entre sistemas diferentes?<\/li>\n\n<li><strong>Como funciona a API REST<\/strong>incluindo a forma como os pedidos s\u00e3o efectuados e tratados.<\/li>\n\n<li><strong>M\u00e9todos de autentica\u00e7\u00e3o<\/strong>A sua experi\u00eancia com a autentica\u00e7\u00e3o b\u00e1sica, a autentica\u00e7\u00e3o de cookies, o OAuth e as palavras-passe de aplica\u00e7\u00f5es, e por que raz\u00e3o s\u00e3o essenciais.<\/li>\n\n<li><strong>Autentica\u00e7\u00e3o da API REST do WordPress<\/strong>incluindo como utilizar JavaScript e PHP para enviar pedidos autenticados.<\/li><\/ul><figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.00.52-A-clear-and-engaging-illustration-summarizing-the-use-of-WordPress-REST-API-for-development.-Show-a-developer-at-a-computer-screen-creating-custom-end.webp\" alt=\"\" class=\"wp-image-2262\" srcset=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.00.52-A-clear-and-engaging-illustration-summarizing-the-use-of-WordPress-REST-API-for-development.-Show-a-developer-at-a-computer-screen-creating-custom-end.webp 1024w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.00.52-A-clear-and-engaging-illustration-summarizing-the-use-of-WordPress-REST-API-for-development.-Show-a-developer-at-a-computer-screen-creating-custom-end-600x600.webp 600w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.00.52-A-clear-and-engaging-illustration-summarizing-the-use-of-WordPress-REST-API-for-development.-Show-a-developer-at-a-computer-screen-creating-custom-end-100x100.webp 100w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.00.52-A-clear-and-engaging-illustration-summarizing-the-use-of-WordPress-REST-API-for-development.-Show-a-developer-at-a-computer-screen-creating-custom-end-300x300.webp 300w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.00.52-A-clear-and-engaging-illustration-summarizing-the-use-of-WordPress-REST-API-for-development.-Show-a-developer-at-a-computer-screen-creating-custom-end-150x150.webp 150w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.00.52-A-clear-and-engaging-illustration-summarizing-the-use-of-WordPress-REST-API-for-development.-Show-a-developer-at-a-computer-screen-creating-custom-end-768x768.webp 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><h3 class=\"wp-block-heading\">FAQ: Perguntas comuns sobre a API REST e a autentica\u00e7\u00e3o<\/h3><ol class=\"wp-block-list\"><li><strong>Posso utilizar a API REST sem autentica\u00e7\u00e3o?<\/strong><ul class=\"wp-block-list\"><li>Sim, mas apenas para dados p\u00fablicos. Para quaisquer dados sens\u00edveis, precisa de uma autentica\u00e7\u00e3o adequada.<\/li><\/ul><\/li>\n\n<li><strong>A autentica\u00e7\u00e3o b\u00e1sica \u00e9 segura?<\/strong><ul class=\"wp-block-list\"><li>A autentica\u00e7\u00e3o b\u00e1sica n\u00e3o \u00e9 segura para produ\u00e7\u00e3o porque as credenciais s\u00e3o codificadas, n\u00e3o encriptadas. \u00c9 mais adequada para testes ou atrav\u00e9s de HTTPS.<\/li><\/ul><\/li>\n\n<li><strong>Para que s\u00e3o utilizadas as palavras-passe de aplica\u00e7\u00e3o?<\/strong><ul class=\"wp-block-list\"><li>As palavras-passe de aplica\u00e7\u00e3o autenticam os pedidos de API sem partilhar a sua palavra-passe principal do WordPress. Ajudam a integrar aplica\u00e7\u00f5es de terceiros.<\/li><\/ul><\/li><\/ol><figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.03.17-An-illustration-summarizing-common-questions-about-REST-API-and-authentication-for-WordPress.-Include-visual-representations-of-key-FAQ-items_-using-R.webp\" alt=\"\" class=\"wp-image-2263\" srcset=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.03.17-An-illustration-summarizing-common-questions-about-REST-API-and-authentication-for-WordPress.-Include-visual-representations-of-key-FAQ-items_-using-R.webp 1024w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.03.17-An-illustration-summarizing-common-questions-about-REST-API-and-authentication-for-WordPress.-Include-visual-representations-of-key-FAQ-items_-using-R-600x600.webp 600w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.03.17-An-illustration-summarizing-common-questions-about-REST-API-and-authentication-for-WordPress.-Include-visual-representations-of-key-FAQ-items_-using-R-100x100.webp 100w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.03.17-An-illustration-summarizing-common-questions-about-REST-API-and-authentication-for-WordPress.-Include-visual-representations-of-key-FAQ-items_-using-R-300x300.webp 300w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.03.17-An-illustration-summarizing-common-questions-about-REST-API-and-authentication-for-WordPress.-Include-visual-representations-of-key-FAQ-items_-using-R-150x150.webp 150w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.03.17-An-illustration-summarizing-common-questions-about-REST-API-and-authentication-for-WordPress.-Include-visual-representations-of-key-FAQ-items_-using-R-768x768.webp 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><h3 class=\"wp-block-heading\">Pr\u00f3ximos passos<\/h3><ul class=\"wp-block-list\"><li><strong>Pratique a autentica\u00e7\u00e3o<\/strong>: Tente implementar diferentes m\u00e9todos de autentica\u00e7\u00e3o num site WordPress local.<\/li>\n\n<li><strong>Crie pontos de extremidade personalizados<\/strong>: Experimente criar pontos de extremidade personalizados no WordPress para ampliar a funcionalidade da sua API REST.<\/li>\n\n<li><strong>Integra\u00e7\u00e3o de JavaScript e PHP<\/strong>: Pratique o envio de pedidos usando JavaScript (como fetch) e PHP (usando a API HTTP do WordPress).<\/li>\n\n<li><strong>Utilize o Postman para testar<\/strong>: Utilize ferramentas como <a href=\"https:\/\/www.postman.com\/\" target=\"_blank\" rel=\"noopener\">Carteiro<\/a> para testar os seus pontos finais da API REST e praticar o envio de pedidos autenticados.<\/li><\/ul><p>Boa programa\u00e7\u00e3o e continue a explorar! A API REST \u00e9 uma ferramenta poderosa, e se souber como utiliz\u00e1-la, ter\u00e1 acesso a infinitas possibilidades no desenvolvimento web.<\/p><figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.04.49-An-illustration-summarizing-next-steps-for-practicing-WordPress-REST-API-development.-Show-a-developers-workspace-with-elements-like-practicing-diffe.webp\" alt=\"\" class=\"wp-image-2264\" srcset=\"https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.04.49-An-illustration-summarizing-next-steps-for-practicing-WordPress-REST-API-development.-Show-a-developers-workspace-with-elements-like-practicing-diffe.webp 1024w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.04.49-An-illustration-summarizing-next-steps-for-practicing-WordPress-REST-API-development.-Show-a-developers-workspace-with-elements-like-practicing-diffe-600x600.webp 600w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.04.49-An-illustration-summarizing-next-steps-for-practicing-WordPress-REST-API-development.-Show-a-developers-workspace-with-elements-like-practicing-diffe-100x100.webp 100w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.04.49-An-illustration-summarizing-next-steps-for-practicing-WordPress-REST-API-development.-Show-a-developers-workspace-with-elements-like-practicing-diffe-300x300.webp 300w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.04.49-An-illustration-summarizing-next-steps-for-practicing-WordPress-REST-API-development.-Show-a-developers-workspace-with-elements-like-practicing-diffe-150x150.webp 150w, https:\/\/www.openbyt.com\/wp-content\/uploads\/2024\/10\/DALL\u00b7E-2024-10-10-17.04.49-An-illustration-summarizing-next-steps-for-practicing-WordPress-REST-API-development.-Show-a-developers-workspace-with-elements-like-practicing-diffe-768x768.webp 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>","protected":false},"excerpt":{"rendered":"<p>O que \u00e9 a API REST? A API REST (Interface de Programa\u00e7\u00e3o de Aplica\u00e7\u00f5es de Transfer\u00eancia de Estado Representacional) \u00e9 um conjunto de regras que permite que diferentes sistemas de software comuniquem...<\/p>","protected":false},"author":1,"featured_media":3107,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[33,78],"tags":[191,193,192,190],"class_list":["post-1973","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-rest-api","category-rest-api-use","tag-authenticationmethods","tag-javascriptintegration","tag-webdevelopment","tag-wordpressrestapi",""],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/posts\/1973","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/comments?post=1973"}],"version-history":[{"count":11,"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/posts\/1973\/revisions"}],"predecessor-version":[{"id":3191,"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/posts\/1973\/revisions\/3191"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/media\/3107"}],"wp:attachment":[{"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/media?parent=1973"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/categories?post=1973"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.openbyt.com\/pt\/wp-json\/wp\/v2\/tags?post=1973"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}