ARTICLE AD BOX
Introduction
There was a clip erstwhile XMLHttpRequest was utilized to make API requests. It didn’t spot Promises, and it didn’t make for cleanable JavaScript code. Using jQuery, you could usage nan cleaner syntax of jQuery.ajax().
Now, JavaScript has its ain built-in measurement to make API requests. This is nan Fetch API, a caller modular to make server requests pinch Promises, but which too includes further features.
In this tutorial, you will create immoderate GET and POST requests utilizing nan 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 petition nan following:
- A conception betterment business 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 overmuch astir from nan How to Code successful JavaScript series.
- An knowing of Promises successful JavaScript. Read nan Promises conception of this article connected nan arena loop, callbacks, Promises, and async/await successful JavaScript.
Step 1 — Getting Started pinch Fetch API Syntax
One onslaught to utilizing nan Fetch API is by passing fetch() nan URL of nan API arsenic a parameter:
fetch(url)
The fetch() method returns a Promise. After nan fetch() method, spot nan Promise method then():
fetch(url) .then(function() { })
If nan Promise returned is resolve, nan usability incorrect nan then() method is executed. That usability contains nan codification for handling nan accusation received from nan API.
After nan then() method, spot nan 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, nan cull committedness will beryllium returned. The drawback method is utilized to grip reject. The codification incorrect catch() will beryllium executed if an correction occurs erstwhile calling nan API of your choice.
With an knowing of nan syntax for utilizing nan 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 nan JSONPlaceholder API. Using nan API, you will get 10 users and show them connected nan page utilizing JavaScript. This tutorial will retrieve accusation from nan JSONPlaceholder API and show it successful database items incorrect nan author’s list.
Begin by creating an HTML grounds and adding a heading and unordered database pinch nan id of authors:
authors.html
<h1>Authors</h1> <ul id="authors"></ul>
Now adhd book tags to nan bottommost of your HTML grounds and usage a DOM selector to drawback nan ul. Use getElementById pinch authors arsenic nan argument:
authors.html
<h1>Authors</h1> <ul id="authors"></ul> <script> const ul = document.getElementById('authors'); </script>
Remember, authors is nan id for nan antecedently created ul.
Next, create a database that is simply a DocumentFragment:
authors.html
<script> const database = document.createDocumentFragment(); </script>
All nan appended database items will beryllium added to list. A DocumentFragment is not information of nan progressive archive characteristic structure. This has nan usage of not causing performance-affecting redraws erstwhile nan Document Object Model is changed.
Create a changeless adaptable called url which will clasp nan API URL that will return 10 random users:
authors.html
<script> const url = 'https://jsonplaceholder.typicode.com/users'; </script>
Now utilizing nan Fetch API, telephone nan JSONPlaceholder API utilizing fetch() pinch url arsenic nan argument:
authors.html
<script> fetch(url) </script>
You are calling nan Fetch API and passing successful nan URL to nan JSONPlaceholder API. Then a consequence is received. However, nan 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 nan information. To personification nan entity returned into JSON, usage nan json() method.
Add nan then() method which will incorporated a usability pinch a parameter called response:
authors.html
<script> fetch(url) .then((response) => {}) </script>
The consequence parameter takes nan worthy of nan entity returned from fetch(url). Use nan json() method to personification consequence into JSON data:
authors.html
<script> fetch(url) .then((response) => { return response.json(); }) </script>
The JSON accusation still needs to beryllium processed. Add different then() relationship pinch a usability that has an connection 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 constituent 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 practice function, create a adaptable called li that will beryllium group adjacent to createElement pinch li (the HTML element) arsenic nan argument. Also, create an h2 for punishment 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 punishment = document.createElement('h2'); let email = document.createElement('span'); }); }) </script>
The h2 constituent will incorporated nan punishment of nan author. The span constituent will incorporated nan email of nan author. The innerHTML spot and drawstring interpolation will fto 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 punishment = document.createElement('h2'); let email = document.createElement('span'); name.innerHTML = `${author.name}`; email.innerHTML = `${author.email}`; }); }) </script>
Next, nexus 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 punishment = 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 constituent is being appended to nan DocumentFragment list. Once nan practice is complete, nan database is appended to nan ul unordered database element.
With immoderate then() functions completed, you tin now adhd nan catch() function. This usability will log nan imaginable correction to nan console:
authors.html
<script> fetch(url) .then((response) => { }) .then((data) => { }) .catch(function(error) { console.log(error); }); </script>
This is nan afloat codification of nan 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 punishment = 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 nan JSONPlaceholder API and nan Fetch API. In nan 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 nan headers, and nonstop data. Let’s create a POST request.
First, spot a changeless adaptable that holds nan nexus to nan JSONPlaceholder API:
new-author.js
const url = 'https://jsonplaceholder.typicode.com/users';
Next, you petition to group your entity and locomotion it arsenic nan 2nd connection of nan fetch function. This will beryllium an entity called accusation pinch nan cardinal punishment and worthy Sammy (or your name):
new-author.js
let accusation = { name: 'Sammy' }
Since this is simply a POST request, you will petition to authorities that explicitly. Create an entity called fetchData:
new-author.js
let fetchData = { }
This entity needs to spot 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 personification nan worthy 'POST'. assemblage will beryllium group adjacent to nan JSON.stringify() format of nan accusation entity that was conscionable created. headers will personification nan worthy of 'Content-Type': 'application/json; charset=UTF-8'.
The Headers interface is simply a spot of nan 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 proviso you pinch overmuch information.
With this codification successful place, nan POST petition tin beryllium made utilizing nan Fetch API. You will spot url and fetchData arsenic arguments for your fetch POST request:
new-author.js
fetch(url, fetchData)
The then() usability will spot codification that handles nan consequence received from nan JSONPlaceholder API:
new-author.js
fetch(url, fetchData) .then(function() { });
This is nan afloat codification of nan petition you created:
new-author.js
const url = 'https://jsonplaceholder.typicode.com/users'; let accusation = { 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 locomotion fetch() a Request object.
new-author-request.js
const url = 'https://jsonplaceholder.typicode.com/users'; let accusation = { 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 nan sole connection for fetch(), replacing url and fetchData.
Now you cognize 2 methods for creating and executing POST requests pinch nan 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 nan 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 too provides nan expertise to intercept requests and responses, toggle style data, and cancel requests.
Many JavaScript frameworks, specified arsenic React, Vue.js, and Angular, personification their ain built-in methods for making web requests. These methods are often based connected nan Fetch API aliases Axios, but they whitethorn personification further features aliases beryllium overmuch tightly integrated pinch nan 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 nan amended choice.
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 incorrect useEffect() to fetch accusation 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, spot utilizing JavaScript Performance API.
2. Fetch API successful Vue.js
In Vue.js, Fetch API is commonly utilized incorrect nan 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 incorrect services utilizing HttpClient, but if utilizing autochthonal Fetch API, you tin instrumentality it incorrect a component:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-data', template: '<p>{{ accusation | 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 overmuch 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 accusation 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 position from a placeholder API and logs it to nan console. You tin too 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 accusation from an API successful JavaScript?
Fetching JSON accusation 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 nan consequence to JSON utilizing .json() and past processes nan data. If you’re moving pinch capacity optimizations, you whitethorn too find JavaScript Performance API useful.
4. How to fetch accusation from an API pinch JavaScript?
o fetch accusation asynchronously, usage fetch() incorrect an async usability pinch await:
async function fetchData() { try { const consequence = await fetch('https://api.example.com/data'); const accusation = 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, spot learning astir GraphQL API arsenic an replacement to REST APIs.
5. What is nan value betwixt REST API and 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 too 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 accusation guidelines disposable complete nan web.
Conclusion
While nan Fetch API is not yet supported by each nan browsers, it is simply a awesome replacement to XMLHttpRequest.
This tutorial provides a step-by-step line connected utilizing Fetch API successful JavaScript. However, if you’re moving connected a larger project, you whitethorn want to investigation Axios for amended correction handling aliases GraphQL for overmuch businesslike accusation 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 accusation successful immoderate JavaScript project.
If you would for illustration to study really to telephone Web APIs utilizing React, cheque retired this article connected this very topic.