CodeBlanks Logo Icon CodeBlanks

fetch basics

JavaScript course · Intermediate · Lesson 84/134

Learn to make a GET request with fetch and the Response object.

What is fetch?

fetch is the standard way to send an HTTP request to a server in modern browsers. It takes a URL as its first parameter and returns a Promise that resolves with a Response object.

const response = await fetch('https://api.example.com/users');

The returned Response object represents the answer to the request: it gives access to the status code, headers and body. By default fetch makes a GET request, so it only reads data and does not change anything on the server. You wait for the promise with await to handle the answer.

The Response object

When a fetch call completes, it gives you a Response object. Through this object you read the main properties of the answer.

console.log(response.status);
console.log(response.ok);
console.log(response.headers.get('Content-Type'));

status gives the HTTP status code (for example 200, 404), while ok tells you whether the request succeeded as true or false. Through headers you can reach each header of the response. These are only the top-level details of the answer; the body is read separately.

Exercise Make a GET request and log the status code

The url variable holds an address. Use await fetch(url) to put the response into a response variable and log response.status with console.log.

Show example solution
const response = await fetch(url);
console.log(response.status);

Test yourself

  1. Which is a valid fetch call?

    // A
    fetch('https://api.example.com/users'
    // B
    fetch('https://api.example.com/users');
    // C
    fetch https://api.example.com/users;
    // D
    fetch[url];
    • A
    • B
    • C
    • D
    Show answer

    B — Correct! fetch takes a single string parameter: the URL.

  2. Wait for the fetch promise

    const response = ____ fetch('https://api.example.com/users');
    Show answer
    const response = await fetch('https://api.example.com/users');
  3. Match concepts to their meanings

    fetch(url)
    Sends a request to the server
    Response
    Represents the answer from the server
    response.status
    Gives the HTTP status code

All lessons in Intermediate