How to use JavaScript Fetch API to Get Data ?
Last Updated :
12 Jan, 2023
The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests.Â
Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity, and a few more. However, the most prominent ones we use are method, headers, and body.
The method is used to create, read, update and delete data, and hence we have methods like GET, POST, PUT and DELETE.
As an example we would use the API: https://reqres.in/arpi/users which would give us random data about a person, our goal here is to see what is presented in this data.Â
Syntax:Â
fetch(URL, options)
Parameters: This method accepts two parameters as shown above and described below:
- URL: This is the endpoint of the resource from where you want to fetch data.
- Options: This is an optional parameter, it is an options object that can have the following values:
- Method: This denotes the method type, it can be of any HTTP request type, like GET, POST, PUT, DELETE, etc.
- Headers: In case we are passing data to the server, we need to additionally tell fetch that we are going to pass data in form of json/text, etc. Â
- Body: In this part, we actually pass the data as a JSON.
Example 1: GET Request demonstration.
JavaScript
fetch("https://reqres.in/api/users")
.then(res => res.json())
.then(data => console.log(data))
Output: This is what the API is returning to us, some random data about people.
{page: 1, per_page: 6, total: 12, total_pages: 2, data: Array(6), …}
data
:(6) [{…}, {…}, {…}, {…}, {…}, {…}]
page
:1
per_page
:6
support
:{url:
'https://reqres.in/#support-heading', text: 'To keep ReqRes free,
contributions towards server costs are appreciated!'}
total
:12
total_pages
:2
[[Prototype]]
:Object
Example 2: POST Request demonstration. We will now post some random data by ourselves, with the help of the POST method.Â
JavaScript
fetch("https://reqres.in/api/users", {
// Defining method type as POST
method: 'POST',
// Fetch knows, what type of data are we dealing with
headers: {
'Content-Type': 'application/json'
},
// Data needs to be parsed into JSON
body: JSON.stringify({
name: 'Geeks For Geeks',
website: 'https://www.geeksforgeeks.org/',
})
}).then(res => {
return res.json()
}).then(data => console.log(data));
Output: Here, we see that we have successfully made a POST request using fetch API.Â
{name:
'Geeks For Geeks', website: 'https://www.geeksforgeeks.org/',
id: '96',
createdAt: '2023-01-11T06:53:03.680Z'}
Similar Reads
How To Use JavaScript Fetch API To Get Data? An API is a set of rules, protocols, and tools that allows different software applications to communicate with each other. One of the popular ways to perform API requests in JavaScript is by using Fetch API. What is the Fetch API?The Fetch API is a built-in JavaScript feature that allows you to make
4 min read
How to Fetch XML with Fetch API in JavaScript ? The JavaScript fetch() method retrieves resources from a server and produces a Promise. We will see how to fetch XML data with JavaScript's Fetch API, parse responses into XML documents, and utilize DOM manipulation for streamlined data extraction with different methods. These are the following meth
3 min read
How to Make GET call to an API using Axios in JavaScript? Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain JavaScript o
3 min read
How to connect to an API in JavaScript ? An API or Application Programming Interface is an intermediary which carries request/response data between the endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms th
5 min read
What is the use of the Fetch API in JavaScript ? The Fetch API in JavaScript provides a modern, powerful, and flexible way to make HTTP requests from web browsers or Node.js environments. Its primary purpose is to facilitate fetching resources, typically data, from servers or other sources across the web. In simple terms, the Fetch API in JavaScri
2 min read
How To Fetch Data From APIs In NextJS? Fetching data from APIs in Next.js can be done using built-in methods like getServerSideProps, getStaticProps, or client-side fetching with useEffect. This flexibility supports both server-side and static data fetching.Prerequisites:NPM & NodeJSReactJSReact HooksReact RouterApproachTo fetch data
2 min read
How to Access XML Data via JavaScript ? XML stands for Extensible Markup Language. It is a popular format for storing and exchanging data on the web. It provides a structured way to represent data that is both human-readable and machine-readable. There are various approaches to accessing XML data using JavaScript which are as follows: Tab
2 min read
Fetch API in JavaScript The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests. It replaces the older XMLHttpRequest method and provides a cleaner and more flexible way to fetch resources asynchronously. The Fetch API uses Promises, making it easier to work with asynchronous data.Syntaxfetc
6 min read
How To Fetch And Parse RSS Feeds In JavaScript? RSS (Really Simple Syndication) feeds are widely used for sharing updates from websites in a standardized XML format. By fetching and parsing RSS feeds, you can access the latest content from blogs, news sites, and other platforms. In this article, weâll explore how to fetch and parse RSS feeds usin
4 min read
How to Fetch Data From an API in ReactJS? ReactJS provides several ways to interact with APIs, allowing you to retrieve data from the server and display it in your application. In this article, weâll walk you through different methods to fetch data from an API in ReactJS, including using the built-in fetch method, axios, and managing the st
8 min read