How to Use JavaScript Fetch API: Step-by-Step Guide with Examples

Feb 07, 2025 10:28 AM - 1 month ago 52750

Introduction

There was a clip erstwhile XMLHttpRequest was utilized to make API requests. It didn’t see Promises, and it didn’t make for cleanable JavaScript code. Using jQuery, you could usage the cleaner syntax of jQuery.ajax().

Now, JavaScript has its ain built-in measurement to make API requests. This is the Fetch API, a caller modular to make server requests pinch Promises, but which besides includes further features.

In this tutorial, you will create some GET and POST requests utilizing the Fetch API.

Deploy your frontend applications from GitHub utilizing DigitalOcean App Platform. Let DigitalOcean attraction connected scaling your app.

Prerequisites

To complete this tutorial, you will request the following:

  • A section improvement situation for Node.js. Follow How to Install Node.js and Create a Local Development Environment.
  • A basal knowing of coding successful JavaScript, which you tin study much astir from the How to Code successful JavaScript series.
  • An knowing of Promises successful JavaScript. Read the Promises section of this article connected the arena loop, callbacks, Promises, and async/await successful JavaScript.

Step 1 — Getting Started pinch Fetch API Syntax

One attack to utilizing the Fetch API is by passing fetch() the URL of the API arsenic a parameter:

fetch(url)

The fetch() method returns a Promise. After the fetch() method, see the Promise method then():

fetch(url) .then(function() { })

If the Promise returned is resolve, the usability wrong the then() method is executed. That usability contains the codification for handling the information received from the API.

After the then() method, see the catch() method:

fetch(url) .then(function() { }) .catch(function() { });

The API you telephone utilizing fetch() whitethorn beryllium down aliases different errors whitethorn occur. If this happens, the cull committedness will beryllium returned. The drawback method is utilized to grip reject. The codification wrong catch() will beryllium executed if an correction occurs erstwhile calling the API of your choice.

With an knowing of the syntax for utilizing the Fetch API, you tin now move connected to utilizing fetch() connected a existent API.

Step 2 — Using Fetch to get Data from an API

The pursuing codification samples will beryllium based connected the JSONPlaceholder API. Using the API, you will get 10 users and show them connected the page utilizing JavaScript. This tutorial will retrieve information from the JSONPlaceholder API and show it successful database items wrong the author’s list.

Begin by creating an HTML record and adding a heading and unordered database pinch the id of authors:

authors.html

<h1>Authors</h1> <ul id="authors"></ul>

Now adhd book tags to the bottommost of your HTML record and usage a DOM selector to drawback the ul. Use getElementById pinch authors arsenic the argument:

authors.html

<h1>Authors</h1> <ul id="authors"></ul> <script> const ul = document.getElementById('authors'); </script>

Remember, authors is the id for the antecedently created ul.

Next, create a database that is simply a DocumentFragment:

authors.html

<script> const database = document.createDocumentFragment(); </script>

All the appended database items will beryllium added to list. A DocumentFragment is not portion of the progressive archive character structure. This has the use of not causing performance-affecting redraws erstwhile the Document Object Model is changed.

Create a changeless adaptable called url which will clasp the API URL that will return 10 random users:

authors.html

<script> const url = 'https://jsonplaceholder.typicode.com/users'; </script>

Now utilizing the Fetch API, telephone the JSONPlaceholder API utilizing fetch() pinch url arsenic the argument:

authors.html

<script> fetch(url) </script>

You are calling the Fetch API and passing successful the URL to the JSONPlaceholder API. Then a consequence is received. However, the consequence you get is not JSON, but an entity pinch a bid of methods that tin beryllium utilized depending connected what you want to do pinch the information. To person the entity returned into JSON, usage the json() method.

Add the then() method which will incorporate a usability pinch a parameter called response:

authors.html

<script> fetch(url) .then((response) => {}) </script>

The consequence parameter takes the worth of the entity returned from fetch(url). Use the json() method to person consequence into JSON data:

authors.html

<script> fetch(url) .then((response) => { return response.json(); }) </script>

The JSON information still needs to beryllium processed. Add different then() connection pinch a usability that has an statement called data:

authors.html

<script> fetch(url) .then((response) => { return response.json(); }) .then((data) => {}) </script>

Within this function, create a adaptable called authors that is group adjacent to data:

authors.html

<script> fetch(url) .then((response) => { return response.json(); }) .then((data) => { let authors = data; }) </script>

For each writer successful authors, you will want to create a database point that displays their name. The map() method is suited for this pattern:

authors.html

<script> fetch(url) .then((response) => { return response.json(); }) .then((data) => { let authors = data; authors.map(function(author) { }); }) </script>

Within your representation function, create a adaptable called li that will beryllium group adjacent to createElement pinch li (the HTML element) arsenic the argument. Also, create an h2 for sanction and a span for email:

authors.html

<script> fetch(url) .then((response) => { return response.json(); }) .then((data) => { let authors = data; authors.map(function(author) { let li = document.createElement('li'); let sanction = document.createElement('h2'); let email = document.createElement('span'); }); }) </script>

The h2 constituent will incorporate the sanction of the author. The span constituent will incorporate the email of the author. The innerHTML spot and drawstring interpolation will let you to do this:

authors.html

<script> fetch(url) .then((response) => { return response.json(); }) .then((data) => { let authors = data; authors.map(function(author) { let li = document.createElement('li'); let sanction = document.createElement('h2'); let email = document.createElement('span'); name.innerHTML = `${author.name}`; email.innerHTML = `${author.email}`; }); }) </script>

Next, link these DOM elements pinch appendChild:

authors.html

<script> fetch(url) .then((response) => { return response.json(); }) .then((data) => { let authors = data; authors.map(function(author) { let li = document.createElement('li'); let sanction = document.createElement('h2'); let email = document.createElement('span'); name.innerHTML = `${author.name}`; email.innerHTML = `${author.email}`; li.appendChild(name); li.appendChild(email); list.appendChild(li); }); }) ul.appendChild(list); </script>

Note that each database point is being appended to the DocumentFragment list. Once the representation is complete, the database is appended to the ul unordered database element.

With some then() functions completed, you tin now adhd the catch() function. This usability will log the imaginable correction to the console:

authors.html

<script> fetch(url) .then((response) => { }) .then((data) => { }) .catch(function(error) { console.log(error); }); </script>

This is the afloat codification of the petition you created:

authors.html

<h1>Authors</h1> <ul id="authors"></ul> <script> const ul = document.getElementById('authors'); const database = document.createDocumentFragment(); const url = 'https://jsonplaceholder.typicode.com/users'; fetch(url) .then((response) => { return response.json(); }) .then((data) => { let authors = data; authors.map(function(author) { let li = document.createElement('li'); let sanction = document.createElement('h2'); let email = document.createElement('span'); name.innerHTML = `${author.name}`; email.innerHTML = `${author.email}`; li.appendChild(name); li.appendChild(email); list.appendChild(li); }); }). .catch(function(error) { console.log(error); }); ul.appendChild(list); </script>

You conscionable successfully performed a GET petition utilizing the JSONPlaceholder API and the Fetch API. In the adjacent step, you will execute POST requests.

Step 3 — Handling POST Requests

Fetch defaults to GET requests, but you tin usage each different types of requests, alteration the headers, and nonstop data. Let’s create a POST request.

First, see a changeless adaptable that holds the nexus to the JSONPlaceholder API:

new-author.js

const url = 'https://jsonplaceholder.typicode.com/users';

Next, you request to group your entity and walk it arsenic the 2nd statement of the fetch function. This will beryllium an entity called information pinch the cardinal sanction and worth Sammy (or your name):

new-author.js

let information = { name: 'Sammy' }

Since this is simply a POST request, you will request to authorities that explicitly. Create an entity called fetchData:

new-author.js

let fetchData = { }

This entity needs to see 3 keys: method, body, and headers:

new-author.js

let fetchData = { method: 'POST', body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json; charset=UTF-8' }) }

The method cardinal will person the worth 'POST'. assemblage will beryllium group adjacent to the JSON.stringify() format of the information entity that was conscionable created. headers will person the worth of 'Content-Type': 'application/json; charset=UTF-8'.

The Headers interface is simply a spot of the Fetch API, which allows you to execute actions connected HTTP petition and consequence headers. This article called How To Define Routes and HTTP Request Methods successful Express tin supply you pinch much information.

With this codification successful place, the POST petition tin beryllium made utilizing the Fetch API. You will see url and fetchData arsenic arguments for your fetch POST request:

new-author.js

fetch(url, fetchData)

The then() usability will see codification that handles the consequence received from the JSONPlaceholder API:

new-author.js

fetch(url, fetchData) .then(function() { });

This is the afloat codification of the petition you created:

new-author.js

const url = 'https://jsonplaceholder.typicode.com/users'; let information = { name: 'Sammy' } let fetchData = { method: 'POST', body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json; charset=UTF-8' }) } fetch(url, fetchData) .then(function() { });

Alternatively, you tin walk fetch() a Request object.

new-author-request.js

const url = 'https://jsonplaceholder.typicode.com/users'; let information = { name: 'Sammy' } let petition = new Request(url, { method: 'POST', body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json; charset=UTF-8' }) }); fetch(request) .then(function() { });

With this approach, petition tin beryllium utilized arsenic the sole statement for fetch(), replacing url and fetchData.

Now you cognize 2 methods for creating and executing POST requests pinch the Fetch API.

Comparison pinch Axios and Framework Integrations

The Fetch API is simply a modern and elastic interface for making web requests successful JavaScript. It is promise-based, making it easier to grip asynchronous operations efficiently. However, it is not the only action for making web requests successful JavaScript.

Axios is simply a celebrated room for making HTTP requests successful JavaScript. It is promise-based and has a elemental and cleanable API. It besides provides the expertise to intercept requests and responses, toggle shape data, and cancel requests.

Many JavaScript frameworks, specified arsenic React, Vue.js, and Angular, person their ain built-in methods for making web requests. These methods are often based connected the Fetch API aliases Axios, but they whitethorn person further features aliases beryllium much tightly integrated pinch the framework’s ecosystem.

If you’re moving connected a elemental task and for illustration a lightweight, autochthonal solution, usage Fetch API. However, for projects requiring automatic JSON parsing, interceptors, and amended correction handling, Axios is the amended choice.

Feature Fetch API Axios
Native Support Built-in successful JavaScript Requires installation (npm instal axios)
Response Handling Needs response.json() to parse JSON Auto-parses JSON responses
Error Handling Requires manual correction handling Better built-in correction handling
Request Cancellation Not built-in (needs AbortController) Supports petition cancellation
Interceptors Not supported Supports request/response interceptors

You tin cheque retired How to Use Vue.js and Axios to Display Data from an API for an Axios-based approach.

Using Fetch API successful JavaScript Frameworks

1. Fetch API successful React

React applications often usage Fetch API wrong useEffect() to fetch information erstwhile a constituent mounts:

import { useState, useEffect } from 'react'; function App() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(json => setData(json)) .catch(error => console.error('Error fetching:', error)); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; } export default App;

For amended capacity successful React, see utilizing JavaScript Performance API.

2. Fetch API successful Vue.js

In Vue.js, Fetch API is commonly utilized wrong the mounted() lifecycle hook:

<script> export default { data() { return { data: null }; }, async mounted() { effort { const consequence = await fetch('https://api.example.com/data'); this.data = await response.json(); } drawback (error) { console.error('Error fetching:', error); } } }; </script>

Alternatively, galore Vue.js projects for illustration utilizing Axios for its simplicity, arsenic shown successful How to Use Vue.js and Axios to Display Data from an API.

3. Fetch API successful Angular

In Angular, Fetch API tin beryllium utilized wrong services utilizing HttpClient, but if utilizing autochthonal Fetch API, you tin instrumentality it wrong a component:

import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-data', template: '<p>{{ information | json }}</p>' }) export class DataComponent implements OnInit { data: any; async ngOnInit() { try { const consequence = await fetch('https://api.example.com/data'); this.data = await response.json(); } catch (error) { console.error('Error fetching:', error); } } }

For ample applications, Angular’s built-in HttpClientModule is recommended for amended scalability.

FAQs

1. What does Fetch API do successful JavaScript?

The Fetch API provides a modern and elastic interface for making web requests successful JavaScript. It allows you to fetch resources for illustration JSON data, HTML, images, and much from a server. Unlike older methods for illustration XMLHttpRequest, Fetch API is promise-based, making it easier to grip asynchronous operations efficiently.

2. What is an illustration of Fetch API?

A elemental illustration of utilizing Fetch API to petition JSON information from an API:

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

This fetches a sample station from a placeholder API and logs it to the console. You tin besides cheque retired How to Use Vue.js and Axios to Display Data from an API for different measurement to retrieve and show API data.

3. How to fetch JSON information from an API successful JavaScript?

Fetching JSON information utilizing Fetch API follows a elemental pattern:

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

This converts the consequence to JSON utilizing .json() and past processes the data. If you’re moving pinch capacity optimizations, you whitethorn besides find JavaScript Performance API useful.

4. How to fetch information from an API pinch JavaScript?

o fetch information asynchronously, usage fetch() wrong an async usability pinch await:

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

This ensures cleaner codification and amended correction handling. For precocious API integrations, see learning astir GraphQL API arsenic an replacement to REST APIs.

5. What is the quality betwixt REST API and Fetch API?

Feature REST API Fetch API
Architecture REST API is an architectural style utilized for designing networked applications. Fetch API is simply a JavaScript interface utilized to make HTTP requests.
HTTP Methods REST API relies connected HTTP methods (GET, POST, PUT, DELETE, etc.) to entree resources. Fetch API besides supports these HTTP methods.
Resource Access REST API is utilized to entree resources. Fetch API tin beryllium utilized to entree a REST API aliases different web resources.

In simpler terms, Fetch API is simply a instrumentality utilized to interact pinch a REST API aliases immoderate different information root disposable complete the web.

Conclusion

While the Fetch API is not yet supported by each the browsers, it is simply a awesome replacement to XMLHttpRequest.

This tutorial provides a step-by-step guideline connected utilizing Fetch API successful JavaScript. However, if you’re moving connected a larger project, you whitethorn want to research Axios for amended correction handling aliases GraphQL for much businesslike information fetching.

Next Steps

  • Learn really to optimize API capacity pinch JavaScript Performance API.
  • Explore GraphQL for an replacement to REST APIs.
  • Read How to Use Vue.js and Axios to Display Data from an API for a comparison pinch Axios.

By integrating these concepts, you tin efficiently fetch and negociate information successful immoderate JavaScript project.

If you would for illustration to study really to telephone Web APIs utilizing React, check retired this article connected this very topic.

More