Fetch API Fun: Beginner's Guide to Web Requests 🔎🌐

arjuncodess

Arjun Vijay Prakash

Posted on April 6, 2024

Fetch API Fun: Beginner's Guide to Web Requests 🔎🌐

Interacting with external APIs, or Application Programming Interfaces, has become an essential skill in web development.

Learn the essentials of Fetch API with this and continue your learning journey with resource links at the end of the article.

In programming, when we want to get information from other places on the internet, we use something called an API.

One tool we use to talk to APIs in JavaScript is called the Fetch API.

Today, we're going to learn all about the Fetch API, and how it works, and I'll show you a fun example so you can try it out yourself.


1️⃣ What is Fetch API? + Usage

The Fetch API is a JavaScript interface for making network requests, including fetching data from a server or sending data to a server using HTTP.

The Fetch API is a Modern, promise-based JavaScript API for making network requests in web applications.

It was introduced to replace the older and less flexible XMLHttpRequest object, which is commonly associated with AJAX.

The Fetch API is also simple to use.

You create a fetch() function that takes a URL as an argument and returns a Promise.

You can then use .then() and .catch() methods to handle the response and any errors.


2️⃣ Key Concepts

➡️ Requests and Responses

The Fetch API involves sending requests
(e.g., GET, POST, PUT, DELETE)
to a URL and receive responses from the server.

➡️ Promises

Fetch API uses JavaScript Promises to handle asynchronous operations, making it more efficient and easier to work with.

➡️ CORS

Cross-Origin Resource Sharing (CORS) is an important consideration when making requests to different domains.

Fetch handles CORS by default.

Learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

➡️ Request Options

You can configure the request by providing various options in the fetch() function, such as method, headers, and body for POST requests.

➡️ Handling Responses

The .then() method is used to handle the response.

You can use methods like .json(), .text(), or .blob() to parse the response based on the expected content type.


3️⃣ More Stuff

➡️ Error Handling

The .catch() method is used to handle errors during the request.

➡️ Headers

You can set headers in the request to provide additional information, like authentication tokens or content type.

➡️ Async/Await

You can also use async/await with Fetch for more concise and readable code.

➡️ Authentication

You can include authentication tokens or credentials when making requests to secure endpoints.

➡️ Cross-Origin Requests

Fetch handles Cross-Origin requests well, and you can use options like mode and credentials to control CORS behaviour.


4️⃣ Code Example

fetch("https://official-joke-api.appspot.com/random_joke")
  .then((response) => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then((data) => {
    console.log("Joke:", data.setup);
    console.log("Punchline:", data.punchline);
  })
  .catch((error) => {
    console.error('There was a problem with your fetch operation:', error);
  });
Enter fullscreen mode Exit fullscreen mode

This makes a GET request to the specified API URL for fetching a random joke.

It first checks if the response is successful (status code 200).

If successful, it parses the response body as JSON.

Then, it logs the setup and punchline of the joke from the retrieved data.

In case of any unsuccessful responses, it catches the error and logs a corresponding message.

PS: copy and paste this code to the console to see the magic happening!


🙌 Final Thoughts

Resources:

Learn the practical usage from these videos:

Dive deep into the topic with the documentation:

Comment your views about this article!

Okay, that's it for today!

I hope you found this article helpful ❤️

Connect with me @ Linktree.

Follow me on @ Twitter. Quality content coming soon!

Happy Coding! 🚀
Thanks for 26359! 🤗

💖 💪 🙅 🚩
arjuncodess
Arjun Vijay Prakash

Posted on April 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related