JavaScript

A simple way to get data from servers or APIs and use it in your website—like asking the internet for information.

fetch()

What is fetch()?

fetch() is a way to request data from the web.

For example, you can use it to get a news article in JSON format from a server or to retrieve weather information from an API.

You can think of it as a delivery service: you provide a URL, and it brings the requested data back to your program.

Basic usage

This is the basic pattern:

JavaScript

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

Here is what happens:

  1. fetch() requests the URL.
  2. The server response is received as response.
  3. The response body is read with .json() or another method.
  4. The resulting value is used as data.

Writing it with async/await

Using async/await often makes asynchronous code easier to read.

JavaScript

async function getData() {
    try {
        const response = await fetch('https://example.com/data.json');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Error:', error);
    }
}

getData();

With await, the code follows a top-to-bottom flow while the asynchronous request is in progress.

What can fetch() do?

GET
Retrieve data. This is the default method.
POST
Send data.
PUT / DELETE
Update or delete data.

For example, this sends form-like data to a server:

JavaScript

fetch('https://example.com/send', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ name: 'Taro', message: 'Hello!' })
});

Common points to remember

Notes for intermediate users