[31]
Why do we need to fetch data from APIs?
Fetching data from APIs is like getting information from a specialized messenger. An API is like a postman who can go to different places and bring back specific information for you. Sometimes, the information we need is stored in special places like other websites or databases. APIs can help us get that information easily. Apps use APIs to add features like displaying the weather, finding nearby locations or logging in with your social media account.
Two common choices to fetch data
Fetch()
A built-in JavaScript function for making HTTP requests to fetch resources, such as data or files, from a specified URL or endpoint.
Syntax
fetch(resource)
fetch(resource, options)
resource
is a string or any other object, including a URL object that provides the URL of the resource you want to fetch. The URL may be relative to the base URL.
options
is a RequestInit
object containing any custom settings that you want to apply to the request.
Return Value
It returns a promise
that resolves to a Response
object.
Example
// Creating a function to fetch data from the API
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data')
if (!response.ok) {
throw new Error('Network response was not OK')
}
const data = await response.json()
console.log(data) // Handling the data here
} catch (error) {
console.error('Error while fetching data: ', error)
}
}
// Call the fetchData whenever required, for example, in a component's useEffect
useEffect(() => {
fetchData()
}, [])
Axios
A popular third-party library for making HTTP requests. It allows you to make GET requests to retrieve data from a specified URL and you can also make POST requests to send data to a server.
Before you use Axios ensure axios
is installed. Open your terminal and navigate to the project directory. Run the following command to install axios.
npm install axios
Example
import axios from 'axios'
// Creating a function to fetch data from the API
async function fetchData() {
try {
const reponse = await axios.get('https://api.example.com/data')
console.log(response.data) // Handling the data here
} catch (error) {
console.error('Error while fetching data: ', error)
}
}
// Call the fetchData whenever required, for example, in a component's useEffect
useEffect(() => {
fetchData()
}, [])
Consider Ky
Before fetch
became widely available, developers relied heavily on axios for making HTTP requests. Axios was popular because it handled many common tasks, like setting default headers or dealing with JSON responses, in a way that was more straightforward than the older XMLHttpRequest
. However, once fetch was introduced, it quickly became the standard due to its simplicity and the fact that it was built into the browser. Ky is a small HTTP client built on top of the fetch API.
API is simpler, i.e., requires approximately half the code.
Ky includes timeout support which fetch lacked.
Retries failed requests which was something you had to implement yourself.
Literally half the code
Go through the series of examples which demonstrates the how utilization of Ky
can halve your code.
Example 1: Asynchronous function named getWeather()
that fetches weather data
export async function getWeather(city: string): Promise<WeatherData> {
const resp = await fetch(`/weather?city=${city}`);
if (!resp.ok) throw resp;
return resp.json() as Promise<WeatherData>;
}
JavaScript Equivalent
export async function getWeather(city) {
const resp = await fetch(`/weather?city=${city}`);
if (!resp.ok)
throw resp;
return resp.json();
}
Ky Equivalent
import ky, { KyResponse } from 'ky'
export async function getWeather(): Promise<WeatherData> {
return ky.get(`/weather?city=${city}`).json<WeatherData>()
}
Example 2: Asynchronous function named updateWeather()
to make a PUT request to update weather data for a given city
export async function updateWeather(city: string, newTemperature: number): Promise<void> {
const resp = await fetch(`/weather/${city}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ temperature: newTemperature }),
});
if (!resp.ok) throw resp
}
JS Equivalent
export async function updateWeather(city, newTemperature) {
const resp = await fetch(`/weather/${city}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ temperature: newTemperature }),
});
if (!resp.ok)
throw resp
}
Ky Equivalent
import ky from 'ky'
export async function updateWeather(city: string, newTemperature: number): Promise<KyResponse> {
return ky.put(`/weather/${city}`, { json: { temperature } })
}