Using fetch() to Get Data in JavaScript

6/29/2025
All Articles

fetch-api-request.png: "JavaScript diagram showing fetch API making HTTP GET request and receiving JSON response

Using fetch() to Get Data in JavaScript

Using fetch() to Get Data in JavaScript

The fetch() API is a modern and powerful way to make HTTP requests in JavaScript. It is built into the browser and provides a simple interface for fetching resources asynchronously.

This guide covers how to use fetch() to get data from an API or server, handle responses, and work with JSON data.

Basic Syntax of fetch()

fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error));
  • url: The endpoint you're requesting data from.

  • options (optional): An object containing request configuration like method, headers, body, etc.


GET Request Example

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log("Fetched data:", data);
  })
  .catch(error => {
    console.error("There was a problem with the fetch operation:", error);
  });

Using fetch() with async/await

async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('HTTP error ' + response.status);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

getData();

Handling Different Response Types

You can work with different response types using the appropriate methods:

// Get plain text
response.text();

// Get Blob (e.g., image)
response.blob();

// Get FormData
response.formData();

Setting Headers and Options

fetch('https://api.example.com/data', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your_token_here'
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Common Use Cases

  • Fetching JSON data from REST APIs

  • Loading configuration files

  • Consuming third-party services

  • Fetching static files like text or images

Conclusion

The fetch() API is a clean and versatile way to retrieve data in JavaScript. It supports both promise-based and async/await patterns, making it suitable for modern web applications.

Mastering fetch() enables you to integrate your front-end with back-end services effectively.

Article