JavaScript

JavaScript Fetch API: A Simple Tutorial with Examples

5 min read Harshit No comments
JavaScript Fetch API

The Fetch API in JavaScript allows you to send HTTP requests and receive data from a server. It is commonly used to get data from APIs without reloading the web page.

For example, you can use the Fetch API to:

  • Get user information from an API.
  • Display products on an e-commerce website.
  • Submit form data to a server.
  • Get weather information from an API.

The fetch() method returns a Promise, which you can handle using .then() or async/await.

1. Basic Fetch API Example

Let’s start with a simple example.

fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('Error:', error);
    });

How Does This Code Work?

  1. fetch() sends a request to the API URL.
  2. response.json() converts the response body into JavaScript data.
  3. console.log(data) displays the received data.
  4. .catch() handles network errors and other rejected promises in the chain.

Open your browser’s developer console to see the result.

2. Fetch API Using Async/Await

You can also use async/await to write cleaner and easier-to-read code.

async function getPost() {
    try {
        const response = await fetch(
            'https://jsonplaceholder.typicode.com/posts/1'
        );

        if (!response.ok) {
            throw new Error('Failed to fetch data');
        }

        const data = await response.json();

        console.log(data);
    } catch (error) {
        console.error('Error:', error.message);
    }
}

getPost();

Explanation

  • async allows the function to use await.
  • await fetch() waits for the HTTP response.
  • response.ok checks whether the HTTP status is in the successful range (200–299).
  • await response.json() reads and parses the response body.
  • try...catch handles errors.

Important: fetch() does not automatically reject its Promise for HTTP errors such as 404 or 500. That’s why checking response.ok is useful.

3. Display API Data on a Web Page

Now, let’s display the fetched post on a web page instead of only showing it in the console.

HTML

<h2 id="post-title">Loading...</h2>
<p id="post-body"></p>

<button onclick="getPost()">Load Post</button>

JavaScript

async function getPost() {
    const title = document.getElementById('post-title');
    const body = document.getElementById('post-body');

    title.textContent = 'Loading...';
    body.textContent = '';

    try {
        const response = await fetch(
            'https://jsonplaceholder.typicode.com/posts/1'
        );

        if (!response.ok) {
            throw new Error('Unable to load post');
        }

        const data = await response.json();

        title.textContent = data.title;
        body.textContent = data.body;
    } catch (error) {
        title.textContent = 'Something went wrong.';
        body.textContent = error.message;
    }
}

This example fetches a post and displays its title and body inside HTML elements.

We use textContent to display API data safely as text instead of interpreting it as HTML.

4. Sending POST Requests with Fetch API

The Fetch API can also send data to a server using a POST request.

async function createPost() {
    try {
        const response = await fetch(
            'https://jsonplaceholder.typicode.com/posts',
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title: 'My First Post',
                    body: 'Learning JavaScript Fetch API',
                    userId: 1
                })
            }
        );

        if (!response.ok) {
            throw new Error('Failed to create post');
        }

        const data = await response.json();

        console.log(data);
    } catch (error) {
        console.error(error.message);
    }
}

createPost();

Explanation

  • method: 'POST' specifies the HTTP request method.
  • headers tells the server that the request body contains JSON.
  • JSON.stringify() converts the JavaScript object into a JSON string.
  • response.json() parses the server’s JSON response.

JSONPlaceholder is a testing API. It simulates creating a post but does not permanently save it.

5. Common Fetch API Errors

Here are some common issues you may face while using the Fetch API.

1. Network error

The server may be unavailable, the internet connection may fail, or the browser may block the request.

2. HTTP error (404 or 500)

Fetch can still resolve successfully when the server returns an HTTP error status. Check response.ok to handle these cases.

3. CORS error

A browser may block a cross-origin request if the server does not allow your website’s origin. You generally need to configure CORS on the server.

4. Invalid JSON

If the response is not valid JSON, response.json() will reject its Promise.

Conclusion

The JavaScript Fetch API is a simple way to communicate with APIs and exchange data with servers. You can use it to retrieve information, display dynamic content, and send data using HTTP methods such as GET and POST.

Start by learning basic fetch() syntax, then practise using async/await, handling errors, and displaying API data on a web page.

Frequently Asked Questions

What is the Fetch API in JavaScript?

The Fetch API is a browser feature that lets JavaScript send HTTP requests and receive responses from servers.

Is Fetch API better than XMLHttpRequest?

Fetch provides a modern Promise-based interface that works naturally with async/await. XMLHttpRequest is an older alternative that is still supported.

Does Fetch API support POST requests?

Yes. You can specify method: 'POST' and provide request headers and a body.

Can Fetch API return JSON data?

Yes. You can use response.json() to read and parse a JSON response body.

Is Fetch API asynchronous?

Yes. The fetch() method returns a Promise, allowing you to handle the response asynchronously.

Leave a comment

Your email address will not be published.