#front end technology
#web development
#javascript

How to use JavaScript Fetch API?

Anonymous

AnonymousOct 08, 2023

How to use JavaScript Fetch API?

The Fetch() API in JavaScript is a built-in method used for making HTTP requests (such as GET, POST, PUT, or DELETE) to a server. It allows developers to retrieve data from a specified URL, which can be in various formats, including JSON, plain text, HTML, XML, or other types.

It is more flexible and modern way for request data from a server compared to older methods like XMLHttpRequest.

Syntax:

fetch("url") //api for the get request
  .then(response => {
    // Handle response
  })
.catch(error => {
    // Handle error
  });

Parameters: This method requires one parameter and accepts two parameters:

  • url (required): The URL of the resource you want to fetch.
  • options (optional): An object containing request options like method, headers, body, etc.

Example 1: In this example, we will see how to use GET request in Fetch API.

fetch("https://type.fit/api/quotes")
       .then((res) => res.json())
       .then((data) => {
            console.log(data)
     })

Output:

Example 2: In this example, we will see how to use Fetch API with async/await.

Note: Using Fetch API based on async and await. It is best approach.

const fetchQuotes = async () => {
  try {
    const response = await fetch("https://type.fit/api/quotes");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("There was a problem fetching the data:", error);
  }
};
// Call the async function
fetchQuotes();

Example 3: In this example, we will see how to use Fetch API with POST request.

const requestOptions = {
  method: "POST", // HTTP method (GET, POST, PUT, DELETE, etc.)
  headers: {
    "Content-Type": "application/json",
    // Add custom headers as needed
  },
  body: JSON.stringify({ key: "value" }), // Request payload
};

fetch("https://example.com/api/data", requestOptions)
  .then((response) => {
    // Handle response
  })
  .catch((error) => {
    // Handle errors
  });

Example 4: In this example, we will see using the Fetch API with FormData to send a POST request with form data to a server:

// Create a new FormData object to hold the form data
const formData = new FormData();

// Add key-value pairs to the FormData object (e.g., form fields)
formData.append("username", "john_doe");
formData.append("email", "john@example.com");
formData.append("avatar", avatarFile); // Assuming avatarFile is a File object

// Define the URL for the POST request
const url = "https://example.com/api/user";

// Define request options, including method, headers, and body
const requestOptions = {
  method: "POST",
  headers: {
    // No need to set 'Content-Type' header; FormData handles it
  },
  body: formData,
};

// Use the Fetch API to send the POST request
fetch(url, requestOptions)
  .then((response) => {
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json();
  })
  .then((data) => {
    console.log("Data received from server:", data);
    // Handle the response data as needed
  })
  .catch((error) => {
    console.error("Error:", error);
    // Handle errors gracefully
  });

Conclusion

In this blog post, we've explored the Fetch API in JavaScript, a modern and flexible way to make HTTP requests to a server. The Fetch API allows developers to interact with server-side resources, retrieve data in various formats, and handle responses and errors efficiently.

Compared to older methods like XMLHttpRequest, the Fetch API provides a cleaner and more intuitive syntax, making it easier to work with asynchronous operations in JavaScript.

We've covered the basics of using the Fetch API for common HTTP request methods like GET and POST. You can use it to retrieve data from a specified URL, send data to a server, and handle responses and errors gracefully.

Additionally, we've seen how to use the Fetch API with both .then() and async/await syntax, demonstrating its flexibility and suitability for different coding styles.

Remember that when using the Fetch API, you can also include various options like custom headers, request methods, and request payloads to tailor your requests to specific server requirements.

In conclusion, the Fetch API is a powerful tool for web developers, allowing them to create dynamic web applications that can communicate with servers seamlessly.

Happy Coding! ❤️