Fetching Data from an API in JavaScript - How to Use Fetch API

JavaScript

readTime

5 min

Fetching Data from an API in JavaScript - How to Use Fetch API

Fetch API in JavaScript: A Beginnerโ€™s Guide ๐ŸŒ

The Fetch API in JavaScript is an incredibly useful tool that simplifies the creation of web applications by handling network requests.

If you are just starting your journey with programming, check out my category getting started with programming.

With Fetch API, you can easily send HTTP requests, retrieve data from APIs, send information to the server, and do all of this asynchronously, which is key in modern applications.

In this post, I'll explain how Fetch API works, how to use different types of requests (GET, POST, PUT, PATCH, DELETE), and how to manage errors and responses from the server.

If you're interested in other web technologies, take a look at my article on what is and how the DOM works.

What is Fetch API in JavaScript? ๐Ÿค”

Fetch API is a built-in interface in browsers that allows you to make asynchronous HTTP requests to the server. Itโ€™s a more modern alternative to the outdated XMLHttpRequest mechanism, offering a clearer and more efficient way to work with data.

Using Fetch API, we can send data in JSON format, as well as use various HTTP methods such as GET, POST, PUT, and DELETE. Moreover, Fetch API uses promises, which allows for elegant error handling through .then() and .catch() methods.

If you want to know more about APIs, check out my post on what is an API.

How Does Fetch API Work? ๐Ÿ”„

Basic use of the Fetch API involves calling the fetch() function, where you pass the URL as a parameter and optionally additional settings such as the method, headers, or request body. Hereโ€™s an example of a simple GET request:

javascript
fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json()) // Convert response to JSON
  .then((data) => console.log(data)) // Display data in the console
  .catch((error) => console.error("Error:", error));

If you're curious to learn more about JavaScript, feel free to read my article on what is JavaScript.

Sending a GET Request with Fetch API ๐Ÿ”Ž

The most commonly used HTTP method is GET, which is used to retrieve data from the server. Example:

javascript
fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json()) // Convert response to JSON
  .then((data) => console.log(data)) // Display data in the console
  .catch((error) => console.error("Error fetching data:", error));

In this case, the GET request fetches a post with ID 1, and the result is processed as JSON.

Using Async/Await with Fetch API

Using async/await simplifies asynchronous code, making it more readable. Hereโ€™s an example:

javascript
async function fetchPost() {
  try {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/posts/1"
    );
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error:", error);
  }
}

fetchPost();

Sending a POST Request with Fetch API ๐Ÿ“

The POST method is used to send data to the server. Hereโ€™s an example:

javascript
fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "New post",
    body: "Content of the new post",
    userId: 1,
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

Sending a PUT Request with Fetch API ๐Ÿ”„

The PUT method is used to update existing resources on the server. Example:

javascript
fetch("https://jsonplaceholder.typicode.com/posts/1", {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    id: 1,
    title: "Updated post",
    body: "Updated content of the post",
    userId: 1,
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

Sending a PATCH Request with Fetch API ๐Ÿ› ๏ธ

Like PUT, the PATCH method is used to update resources, but on a smaller scale:

javascript
fetch("https://jsonplaceholder.typicode.com/posts/1", {
  method: "PATCH",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ title: "Updated title" }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

Deleting Data with Fetch API Using DELETE ๐Ÿšฎ

The DELETE method allows you to delete a resource from the server:

javascript
fetch("https://jsonplaceholder.typicode.com/posts/1", {
  method: "DELETE",
})
  .then((response) => console.log("Post deleted:", response))
  .catch((error) => console.error("Error:", error));

Error Handling in Fetch API โš ๏ธ

Error handling is crucial when using Fetch API. Here's how we can handle a failed request:

javascript
fetch("https://jsonplaceholder.typicode.com/posts/10000")
  .then((response) => {
    if (!response.ok) {
      throw new Error("Error: Failed to fetch data");
    }
    return response.json();
  })
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

Fetch API with React and Node.js ๐ŸŒ

Fetch API works seamlessly with frameworks like React and Node.js. In React, we can use fetch() in combination with useEffect to fetch data from an API.

Example in React:

javascript
import React, { useState, useEffect } from "react";

function App() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => response.json())
      .then((data) => setData(data))
      .catch((error) => console.error("Error:", error));
  }, []);

  return (
    <div>
      {data
        ? data.map((post) => <p key={post.id}>{post.title}</p>)
        : "Loading..."}
    </div>
  );
}

export default App;

Pros and Cons of Fetch API ๐Ÿ“Š

Pros:

  • Simplicity and readability of the code
  • Promise support
  • Versatility

Cons:

  • Lack of support for request cancellation (you can use AbortController)
  • Fetch API does not throw errors for 404 or 500 responses

Summary ๐Ÿ“‹

Fetch API is a great tool that significantly simplifies working with data and network requests in JavaScript. With the ability to use async/await, API handling becomes even easier. If youโ€™re building modern applications, Fetch API is an essential tool in your arsenal.

If you're still wondering if learning programming is worth it, check out my article on is it worth learning programming in 2023.

authorImg

Witek Pruchnicki

I passionately share knowledge about programming and more in various ways.