Guia da API Fetch do JavaScript: GET, POST, Tratamento de Erros e Exemplos do Mundo Real

1. Introdução

JavaScript é uma das linguagens de programação mais amplamente usadas no desenvolvimento web. Entre suas muitas funcionalidades, a Fetch API tem ganhado atenção como uma capacidade importante para habilitar a comunicação assíncrona.

Neste artigo, explicamos a Fetch API em detalhes — desde o básico até usos mais avançados. Ao compreendê‑la, você poderá implementar a obtenção de dados e a comunicação com o servidor de forma mais fluida em aplicações web.

O que é comunicação assíncrona?

Comunicação assíncrona é um método de troca de dados com um servidor enquanto outras tarefas continuam sendo processadas, sem bloquear até que a comunicação termine. Isso melhora a responsividade da interface do usuário e facilita o tratamento de dados sem frustração.

Por exemplo, quando um usuário clica em um botão em uma página web para buscar dados, outras tarefas podem continuar sem aguardar a resposta do servidor, melhorando consideravelmente a experiência do usuário.

O que é a Fetch API?

A Fetch API é uma interface moderna para realizar comunicação assíncrona em JavaScript. Foi introduzida como alternativa ao tradicional XMLHttpRequest (XHR), oferecendo sintaxe concisa e configuração flexível.

Com essa API, você pode escrever facilmente a lógica para recuperar dados de um servidor ou enviar dados para um servidor.

Nas seções seguintes, apresentaremos tudo passo a passo — desde o uso básico da Fetch API até exemplos práticos e reais.

2. O que é a Fetch API?

A Fetch API é a interface padrão mais recente para realizar comunicação assíncrona em JavaScript. Nesta seção, explicamos seu papel básico e como ela difere das abordagens tradicionais.

Visão geral da Fetch API

A Fetch API foi projetada para recuperar recursos através de uma rede.
Isso facilita a comunicação de aplicações web com servidores.

Principais recursos

  • Baseada em Promises : Não é necessário depender de funções de callback, permitindo escrever código mais legível.
  • Sintaxe concisa : Em comparação ao XMLHttpRequest, pode reduzir significativamente a quantidade de código.
  • Alta flexibilidade : Você pode personalizar requisições e respostas em detalhes.
  • Design moderno : Funciona bem com recursos modernos do JavaScript, permitindo código mais sustentável.

Abaixo está um exemplo básico de uso da Fetch API.

fetch('https://api.example.com/data')
  .then(response => response.json()) // Convert to JSON
  .then(data => console.log(data))  // Output the data
  .catch(error => console.error('Error:', error)); // Error handling

Este código busca dados da URL especificada, converte‑os para JSON e os exibe no console. Se ocorrer um erro, ele imprime uma mensagem de erro.

Diferenças em relação ao XMLHttpRequest tradicional

A Fetch API é uma nova abordagem que substitui o amplamente usado XMLHttpRequest (XHR). A tabela abaixo compara as duas.

FeatureFetch APIXMLHttpRequest
Code simplicityConcise, readable syntaxOften complex with many callbacks
Asynchronous handlingSupports Promises and offers high flexibilityRequires callback functions
Stream processingNative supportRequires additional handling
Working with JSONEasy to handleRequires explicit parsing
Error handlingFlexible and can be centralizedOften becomes complex

Como pode ser visto, a Fetch API é atraente por seu design conciso e moderno. Em particular, ser baseada em Promises permite escrever lógica assíncrona de forma mais natural.

Resumo

A Fetch API é uma ferramenta poderosa e fácil de usar para comunicação assíncrona em JavaScript. Por ser mais simples de implementar que o XHR tradicional, tornou‑se uma habilidade essencial para o desenvolvimento web moderno.

Na próxima seção, percorreremos padrões de uso concretos da Fetch API com exemplos de código.

3. Uso básico da Fetch API

Nesta seção, explicamos o uso básico da Fetch API com exemplos de código concretos. Cobremos principalmente os seguintes pontos.

  • Sintaxe do método fetch() e um exemplo básico
  • Como implementar uma requisição GET
  • Como lidar com os dados da resposta

Sintaxe básica do método fetch()

Com a Fetch API, você envia requisições a um servidor usando o método fetch(). Abaixo está a sintaxe básica.

fetch(url, options)
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle errors
  });

Argumentos

  • url : A URL para a qual a requisição é enviada.
  • options (opcional): Configurações de opções que incluem método, cabeçalhos, corpo e mais.

Valor de retorno

  • Objeto Promise : Retorna o resultado do processo assíncrono.

Como implementar uma requisição GET

O uso mais básico da Fetch API é uma requisição GET, que recupera dados de um servidor.

Exemplo: Buscar dados JSON

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network error');
    }
    return response.json(); // Retrieve data as JSON
  })
  .then(data => {
    console.log(data); // Display the retrieved data
  })
  .catch(error => {
    console.error('Error:', error); // Print an error log
  });

Como processar os dados da resposta

Com a Fetch API, você pode processar os dados da resposta em vários formatos. Abaixo estão exemplos comuns.

  1. Recuperar dados de texto
    fetch('https://example.com/data.txt')
      .then(response => response.text()) // Retrieve data as text
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    
  1. Recuperar dados binários
    fetch('https://example.com/image.jpg')
      .then(response => response.blob()) // Retrieve as binary data
      .then(blob => {
        const imgURL = URL.createObjectURL(blob);
        document.querySelector('img').src = imgURL;
      })
      .catch(error => console.error('Error:', error));
    
  1. Recuperar informações de cabeçalho
    fetch('https://example.com/api')
      .then(response => {
        console.log(response.headers.get('Content-Type')); // Get a header value
      })
      .catch(error => console.error('Error:', error));
    

Resumo

Aqui, cobrimos uma requisição GET básica usando a Fetch API e como lidar com as respostas.

A Fetch API é uma ferramenta flexível que facilita a recuperação de vários tipos de dados, como texto, JSON e dados binários. Uma vez que você compreenda esses fundamentos, será mais fácil aplicá-los ao próximo capítulo, incluindo tratamento de erros e requisições POST.

Na próxima seção, explicaremos o tratamento de erros com a Fetch API em detalhes.

4. Tratamento de erros

Nesta seção, explicamos o tratamento de erros ao usar a Fetch API. Ao se comunicar com um servidor, vários problemas podem ocorrer, como erros de rede e erros de resposta. Lidar com eles adequadamente pode melhorar a experiência do usuário.

Noções básicas de tratamento de erros

Com a Fetch API, você pode usar o método catch() para lidar com casos como falhas de rede ou respostas de erro.

Exemplo básico de tratamento de erro

fetch('https://example.com/data')
  .then(response => {
    if (!response.ok) { // Check the response status code
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('An error occurred:', error)); // Error handling

Tratamento de erro com try…catch

Usar Async/Await permite escrever um código mais limpo e legível. Nesse caso, você trata os erros com uma instrução try...catch.

Exemplo: Tratamento de erro com Async/Await

async function fetchData() {
  try {
    const response = await fetch('https://example.com/data');
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('An error occurred:', error);
  }
}

fetchData();

Implementando timeouts

A Fetch API não inclui um recurso de timeout embutido por padrão. No entanto, implementar timeouts permite lidar adequadamente com respostas lentas.

Exemplo: Implementando um timeout

function fetchWithTimeout(url, timeout = 5000) {
  return Promise.race([
    fetch(url),
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('Request timed out')), timeout)
    ),
  ]);
}

fetchWithTimeout('https://example.com/data', 5000)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Ocorreu um erro:', error));

Detecting network errors

A network error refers to cases where the server cannot be reached or the connection is interrupted. With the Fetch API, these errors can also be detected with catch().

Example: Handling a network error

fetch('https://invalid-url.com/data')
  .then(response => response.json())
  .catch(error => console.error('Erro de rede:', error.message));

Summary

In this section, we introduced error handling with the Fetch API, from basics to more advanced patterns.

Key takeaways

  • Check response status codes and implement error handling
  • Simplify error handling with Async/Await
  • Handle slow responses by implementing timeouts

Error handling is critical for improving the user experience. In the next section, we’ll explain POST requests for sending data to a server.

5. Sending POST requests

In this section, we explain how to send POST requests with the Fetch API to send data to a server. We’ll cover practical examples such as sending form data and JSON.

Basic syntax for POST requests

You can implement a POST request in the Fetch API by providing an options object as the second argument to the fetch() method.

Basic syntax

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Erro:', error));

Example: Sending JSON data

Below is an example of sending user information in JSON format.

const userData = {
  name: 'Taro Yamada',
  email: 'yamada@example.com',
};

fetch('https://example.com/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(userData),
})
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log('Sucesso:', data))
  .catch(error => console.error('Erro:', error));

Example: Sending form data

To send form data, use the FormData object.

const formData = new FormData();
formData.append('username', 'yamada');
formData.append('file', fileInput.files[0]);

fetch('https://example.com/upload', {
  method: 'POST',
  body: formData,
})
  .then(response => response.json())
  .then(data => console.log('Upload bem-sucedido:', data))
  .catch(error => console.error('Erro:', error));

Example: Requests with authentication information

When sending data along with authentication information (for example, a token), add the auth data to the request headers.

fetch('https://example.com/api/protected', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify({ message: 'Hello!' }),
})
  .then(response => response.json())
  .then(data => console.log('Sucesso:', data))
  .catch(error => console.error('Erro:', error));

Error handling for POST requests

For POST requests, you can add error handling like the following to deal with network issues or server-side problems.

async function postData(url, data) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const result = await response.json();
    console.log('Sucesso:', result);
  } catch (error) {
    console.error('Ocorreu um erro:', error.message);
  }
}

postData('https://example.com/api/messages', { text: 'Olá!' });

Summary

In this section, we explained the basics and practical usage of POST requests using the Fetch API.

Key takeaways

  1. How to send JSON data and form data
  2. How to implement requests with authentication information
  3. How to strengthen error handling

POST requests are essential for two-way communication with servers. In the next section, we’ll explain customization options for the Fetch API in detail.

6. Other option settings

In this section, we explain various option settings you can specify as the second argument to the Fetch API. By using these, you can easily customize requests and manage authentication information.

Basic option syntax

Fetch API options are specified as an object in the second argument.

fetch(url, {
  method: 'GET',              
  headers: {                  
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify(data), 
  credentials: 'include',     
  mode: 'cors',               
  cache: 'no-cache',          
  redirect: 'follow',         
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Erro:', error));

Details of each option

  1. method (HTTP method)
  • Specifies the HTTP method (for example: GET, POST, PUT, DELETE).
  • The default is GET .
  1. headers (headers)
  • Specifies request headers.
  • Used to define the data format or add authentication information.
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
    }
    
  1. body (sending data)
  • Used to send data to the server with POST or PUT methods.
  1. credentials (managing credentials)
  • Controls whether credentials (cookies or HTTP authentication data) are sent.
ValueDescription
omitDo not send credentials (default)
same-originSend credentials only for same-origin requests
includeSend credentials even for cross-origin requests
  1. mode (CORS policy)
  • Controls cross-origin request behavior.
ValueDescription
corsAllow cross-origin requests (default)
no-corsAllow only simple requests (limited)
same-originAllow requests only to the same origin
  1. cache (cache control)
  • Controls how request caching is used.
ValueDescription
defaultUse the browser’s default cache settings
no-storeDo not use cache; always make a new request
reloadIgnore cache and make a new request
  1. redirect (redirect handling)
  • Specifies how redirects are handled.
ValueDescription
followAutomatically follow redirects (default)
errorTreat redirects as errors
manualHandle redirects manually (controllable in code)

Advanced customization example

Below is an example that combines multiple options.

fetch('https://example.com/api/resource', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify({ message: 'Olá!' }),
  credentials: 'include',
  mode: 'cors',
  cache: 'no-cache',
  redirect: 'follow',
})
  .then(response => response.json())
  .then(data => console.log('Sucesso:', data))
  .catch(error => console.error('Erro:', error));

Summary

In this section, we explained various Fetch API option settings in detail.

Key takeaways

  1. How to customize headers and credentials
  2. Fine-grained settings such as CORS and cache control
  3. Advanced patterns for redirects and error handling

In the next section, we’ll introduce concrete examples of how to use the Fetch API in practice.

7. Practical examples of using the Fetch API

In this section, we explain how you can use the Fetch API in real projects with concrete examples. Through practical scenarios, you’ll build real-world Fetch API skills.

Displaying a list of API data

A common use case in web applications is fetching data from an external API and displaying it as a list. In the example below, we fetch post data from the JSONPlaceholder API and display it as an HTML list.

Code example

const url = 'https://jsonplaceholder.typicode.com/posts';

fetch(url)
  .then(response => {
    if (!response.ok) {
      throw new Error(`Erro HTTP! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(posts => {
    const list = document.getElementById('post-list');
    posts.forEach(post => {
      const listItem = document.createElement('li');
      listItem.textContent = `${post.id}: ${post.title}`;
      list.appendChild(listItem);
    });
  })
  .catch(error => console.error('Erro:', error));

HTML example

<ul id="post-list"></ul>

Submitting a form and registering data

This is an example of registering data from a form input to a server.

Code example

const form = document.getElementById('user-form');
form.addEventListener('submit', async (e) => {
  e.preventDefault();

  const formData = {
    name: document.getElementById('name').value,
    email: document.getElementById('email').value,
  };

  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    });

    if (!response.ok) {
      throw new Error(`Erro HTTP! Status: ${response.status}`);
    }

    const result = await response.json();
    console.log('Registro bem-sucedido:', result);
    alert('O usuário foi registrado!');
  } catch (error) {
    console.error('Erro:', error);
    alert('Ocorreu um erro.');
  }
});

HTML example

<form id="user-form">
  <input type="text" id="name" placeholder="Nome" required />
  <input type="email" id="email" placeholder="Endereço de email" required />
  <button type="submit">Registrar</button>
</form>

File upload

The Fetch API can also handle file uploads. Below is an example of uploading an image file to a server.

Code example

const fileInput = document.getElementById('file-input');
const uploadButton = document.getElementById('upload-button');

uploadButton.addEventListener('click', async () => {
  const file = fileInput.files[0];
  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await fetch('https://example.com/upload', {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`Erro HTTP! Status: ${response.status}`);
    }

    const result = await response.json();
    console.log('Upload bem-sucedido:', result);
    alert('O arquivo foi enviado!');
  } catch (error) {
    console.error('Erro:', error);
    alert('Falha no upload.');
  }
});

HTML example

<input type="file" id="file-input" />
<button id="upload-button">Enviar</button>

Summary

In this section, we introduced practical examples using the Fetch API.

Key takeaways

  1. Creating a dynamic list by displaying API data
  2. Implementing form submission and data registration
  3. Implementing file uploads and search functionality

By using these examples as references, you can build interactive web applications powered by the Fetch API. In the next section, we’ll summarize the entire article and introduce learning resources for your next steps.

8. Summary

In this article, we explained JavaScript’s Fetch API systematically—from the basics to practical use. The Fetch API is a powerful tool that enables asynchronous communication concisely and efficiently, making it essential for modern web application development.

Review of what you learned

  1. Overview and features of the Fetch API
  • The Fetch API is Promise-based, allowing concise and flexible code.
  • Compared to traditional XMLHttpRequest, the syntax is simpler and easier to maintain.
  1. Basic usage and error handling
  • Basic syntax for fetching data with GET requests.
  • By adding error handling and timeout processing, you can implement more robust code.
  1. Sending data with POST requests
  • Exemplos de envio de dados JSON e dados de formulário.
  • Aprendeu como adicionar informações de autenticação e cabeçalhos personalizados.
  1. Usando configurações de opções de forma eficaz
  • Introduziu métodos flexíveis de personalização, como controle de cache, configurações de CORS e gerenciamento de credenciais.
  1. Exemplos práticos
  • Aprendeu o uso real por meio de exemplos como exibição de lista, envio de formulário, upload de arquivos e funcionalidade de busca.

Vantagens e pontos a observar para a Fetch API

Vantagens

  • O código é conciso e altamente legível.
  • Funciona bem com Promises e Async/Await, facilitando a combinação com a sintaxe moderna de JavaScript.
  • Suporta vários formatos de dados, como JSON, dados binários e streams.

Pontos a observar

  • Não há recurso de timeout por padrão, portanto pode ser necessário implementá-lo você mesmo.
  • Não é suportado em navegadores mais antigos (por exemplo, Internet Explorer), portanto considere polyfills ou alternativas, se necessário.

Recursos de aprendizado para os próximos passos

Para aprofundar sua compreensão da Fetch API, use a documentação oficial e os recursos abaixo.

Finalmente

A Fetch API é uma ferramenta poderosa que permite implementar a comunicação com o servidor de forma simples usando técnicas modernas de JavaScript. Ao aplicar o que você aprendeu neste artigo, pode criar aplicações web mais interativas e ricas em recursos.

À medida que o desenvolvimento web continua a evoluir, a integração de APIs e o processamento assíncrono se tornarão ainda mais importantes. Domine a Fetch API e aperfeiçoe suas habilidades práticas!

Próximos passos

  • Tente criar um projeto que use uma API real.
  • Use opções personalizadas para implementar um tratamento de requisições mais avançado.
  • Desafie-se a construir aplicações full‑stack que integrem com um backend server‑side.

Isso conclui o artigo. Esperamos que aprender a Fetch API ajude a melhorar ainda mais suas habilidades!

広告