On this page

The Fetch API

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

The Fetch API is a powerful, modern interface that allows JavaScript to make HTTP requests to servers over the network. Whether you are pulling the latest weather data, fetching a user's profile, or sending a new blog post to a database, fetch is the standard tool for the job in Vanilla JavaScript. It is entirely Promise-based, making it a perfect companion for the async/await syntax learned in the previous lesson.

The Basic Syntax​

At its simplest, fetch() takes one mandatory argument: the URL of the resource you want to fetch. It returns a Promise that resolves into a Response object.


const responsePromise = fetch("https://api.example.com/data");

Crucially, the Response object is not the actual data itself; it is an HTTP response containing headers, status codes, and the body of the data in a raw format. To access the data, you must use a method like .json() to parse it.

Performing a GET Request​

A GET request is used to retrieve data from a server. Because fetch is asynchronous, the most professional way to implement this is within an async function.


async function getWeatherData() {

  try {

    // 1. Make the request

    const response = await fetch("https://api.weatherapi.com/v1/current.json");



    // 2. Check if the request was successful

    if (!response.ok) {

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

    }



    // 3. Parse the data as JSON

    const data = await response.json();



    console.log("Current Temperature:", data.current.temp_c);

  } catch (error) {

    console.error("Could not fetch weather:", error);

  }

}

Understanding response.ok​

The Fetch Promise only rejects if there is a network failure (like being offline). It will not reject if the server returns an error code like 404 (Not Found) or 500 (Server Error). You must manually check response.ok (which is true for status codes 200–299) to ensure the request truly succeeded.

Performing a POST Request​

A POST request is used to send new data to a server (for example, creating a new user account). This requires a second argument in the fetch() function: an options object.


async function createPost() {

  const newPost = {

    title: "Learning Fetch",

    body: "The Fetch API is much cleaner than the old XHR methods!",

    userId: 1,

  };



  const response = await fetch("https://jsonplaceholder.typicode.com/posts", {

    method: "POST", // Specify the method

    headers: {

      "Content-Type": "application/json", // Tell the server we are sending JSON

    },

    body: JSON.stringify(newPost), // Convert the JS object to a JSON string

  });



  const result = await response.json();

  console.log("Success:", result);

}

Key Components of a Request​

When making network requests, you will frequently interact with these three concepts:

ComponentDescriptionURLThe endpoint or "address" of the API you are calling.HeadersMetadata about the request, such as authentication tokens or data types.BodyThe actual data you are sending (used in POST, PUT, and PATCH).

Handling Errors Professionally​

Network requests are unpredictable. A user might lose their Wi-Fi connection, or a server might go down. Always wrap your fetch calls in a try/catch block to handle these two types of errors:

  1. Network Errors: Caught by the catch block (e.g., DNS failure, lost connection).
  2. Application Errors: Handled by checking response.ok (e.g., 401 Unauthorized, 404 Not Found).

Implementation Checklist​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Async/Await

Next

Advanced Engine Concepts