How to use fetch in JavaScript
Makoto Tsuga
Posted on June 4, 2024
Hello, everyone. In this article, I would explain fetch in JavaScript. It is recommended to read the following article and understand the concept of asynchronous, synchronous processing and Promise before reading this article. This is because these concepts are connected with fetch.
➡async/sync in Javascript
➡How to use Async/Await in Promise.
➡How to use chaining in Promise.
What is fetch?
Fetch is the function can get the local or outside data. This function
asynchronously is executed. By using the function, you can get the many type of data such as text, json, image so on. Please look at following image, in this case, this code can get the information from the json file named "sample.json".
sample.json
{
"name": "makoto",
"gender": "male"
}
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
const test = async ()=>{
const response = await fetch('sample.json')
const data = await response.json()
console.log(data)
}
test();
</script>
console
Thus, fetch can be used to retrieve data from other files and other websites.
How to use it.
This is basic format for fetch. fetch('sample.json') requests data from the file 'sample.json' and returns a Promise object representing the result of the request. And await response.json() retrieves the JSON object (the content we want to obtain) from the response (a Promise object) obtained from the fetch() request.
<script>
const test = async ()=>{
const response = await fetch('sample.json')//get the promise object
const data = await response.json()//get the json object
console.log(data)
}
test();
</script>
Specify the path or URL of the file from which you want to fetch data as an argument to fetch.
Since fetch is an asynchronous operation, you should use await on the fetch function.
Since fetch is an asynchronous operation, add async to the calling function.
The fetch() method returns a Promise object.
fetch can retrieve data in a variety of formats
fetch can get the data not only json but also other types of data such as text, binary data, Blob(image) and FormData.
const data = await response.json();//json data
const text = await response.text();//text data
const arrayBuffer = await response.arrayBuffer();//array buffer data
const blob = await response.blob();//blob data
const formData = await response.formData();//form data
We have to use different methods depending on the type of data we want to retrieve. In this article, we assume that we are retrieving JSON data, so we will only use response.json().
Example of usage when url is specified for fetch
By specifying an external site's URL in fetch, you can retrieve information from the site. Here, I will use the weather Web API, Open-Meteo, as an example to explain.
Open-Meteois weather API, which provide weather info. By including latitude, longitude, and other parameters in the URL, you can retrieve weather information for that location, such as precipitation probability and temperature.
Since you need to customize the URL based on the information you want, it's important to read the site's documentation and deepen your understanding of the API. The rules for writing URLs differ between Web APIs, so first, visit the site and learn how to use the Web API.
In this case, to obtain the maximum temperature for the 7days, I created the following URL. The location is specified as Toronto, Canada (latitude: 43.67, longitude: -79.4):
https://api.open-meteo.com/v1/forecast?latitude=43.67&longitude=-79.4&daily=temperature_2m_max&timezone=America/Toronto
- For obtaining the maximum temperature, temperature_2m_max was specified in the URL.
- 43.67 was designated for the latitude parameter.
- -79.4 was assigned to the longitude parameter.
- America/Toronto was set for the time zone parameter.
This is JavaScript
<script>
const test = async ()=>{
// parameters for the url
const lat = 43.67;
const long = -79.4;
const tzone = 'America/Toronto';
const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${long}&daily=temperature_2m_max&timezone=${tzone}`);
const data = await response.json()// get the json object
console.log(data.daily.temperature_2m_max)
}
test();
</script>
Using fetch with the previously mentioned URL, I was able to output the maximum temperature to the console. By utilizing external website's web API and fetch in this manner, it becomes feasible to retrieve external data. When specifying a URL, it's important to understand the specifications of each respective web API and include parameters accordingly in the URL.
Posted on June 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.