DEV Community

FakeStandard
FakeStandard

Posted on

Using the Fetch API

Back in the day, we used XMLHttpRequest to call APIs.
Nowadays, we use the Fetch API instead — it gives us a JavaScript Interface to handle HTTP request more cleanly.

Let's take a look at how to use it.

🔍 Basic Fetch Request

Here's the basic flow:

  • Specify the URL you want to call.
  • The first then gets a promise — you use response.json() to parse the response as JSON.
  • The second then handles the parsed JSON data.
  • If the fetch runs into an error that's not a 4xx or 5xx response, the catch block will handle it.
fetch("http://example.com/movies.json")
    .then(response => {
        return response.json();
    })
    .then(json => {
        console.log(json);
    })
    .catch(error => {
        console.error(error);
    });
Enter fullscreen mode Exit fullscreen mode

If the server responds with JSON, you'll need to call response.json() to parse and return it as JSON.
If it returns a different format, you'll have to use another method to handle it.
Here are the five ways to parse a response:

  • arrayBuffer()
  • blob()
  • formData()
  • json()
  • text()

🌰 Request Configuration

Fetch takes a second parameter called RequestInit, which lets you configure the request that things like the HTTP method, headers, body, and so on.

fetch(url, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
        'content-type': 'application/json',
    },
    cache: 'no-cache',
    credentials: 'same-origin',
    mode: 'cors',
})
    .then(response => {
        return response.json();
    })
    .then(json => {
        console.log(json);
    })
    .catch(error => {
        console.error(error);
    });
Enter fullscreen mode Exit fullscreen mode

Here are some of the most common options:

  • method — HTTP request method, like GET, POST, PUT, DELETE, etc.
  • body — The data you want to send to the server.
  • headers — Lets you set custom request headers.
  • cache — Tells the browser how to handle HTTP caching for this request.
  • credentials — Controls whether cookies or credentials are sent with the request.
  • mode — Defines how to handle cross-origin requests.

Here's the full RequestInit interface definition for reference:

interface RequestInit {
    /** A BodyInit object or null to set request's body. */
    body?: BodyInit | null;
    /** A string indicating how the request will interact with the browser's cache to set request's cache. */
    cache?: RequestCache;
    /** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */
    credentials?: RequestCredentials;
    /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */
    headers?: HeadersInit;
    /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */
    integrity?: string;
    /** A boolean to set request's keepalive. */
    keepalive?: boolean;
    /** A string to set request's method. */
    method?: string;
    /** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */
    mode?: RequestMode;
    /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */
    redirect?: RequestRedirect;
    /** A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. */
    referrer?: string;
    /** A referrer policy to set request's referrerPolicy. */
    referrerPolicy?: ReferrerPolicy;
    /** An AbortSignal to set request's signal. */
    signal?: AbortSignal | null;
    /** Can only be null. Used to disassociate request from any Window. */
    window?: null;
}
Enter fullscreen mode Exit fullscreen mode

You can adjust these settings depending on what your request needs.

🧩 Example

Here are a few simple examples.

Get request with query parameters

const params = new URLSearchParams();
params.append("id", "1")

const res = await fetch(`${url}?${params}`)
Enter fullscreen mode Exit fullscreen mode

POST request with JSON data

fetch(url, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
        'content-type': 'application/json',
    }
})
    .then((res) => res.json())
    .then((response) => console.log("Success:", response))
    .catch((error) => console.error("Error:", error));
Enter fullscreen mode Exit fullscreen mode

Uploading a file

var formData = new FormData()
var fileField = document.querySelector("input[type='file']")

formData.append("file", fileField.files[0])

fetch(url, {
    method: 'PUT',
    body: formData
})
    .then((response) => response.json())
    .then((response) => console.log("Success:", response))
    .catch((error) => console.error("Error:", error))
Enter fullscreen mode Exit fullscreen mode

🍺 Wrapping Up

The Fetch API is modern, promise-based, and a lot cleaner than XMLHttpRequest.
Once you get used to it, making HTTP requests in JavaScript becomes way simpler, easier to read, and more maintainable.

Easy fix. Job done ☑️


Thanks for reading!

If you like this article, please don't hesitate to click the heart button ❤️
or follow my GitHub I'd appreciate it.

Top comments (0)