
API is an abbreviation for Application Programming Interface, which is a collection of definitions and protocols for developing and integrating application software. APIs enable your product or service to communicate with other products and services without requiring you to understand how they work. This can help to simplify app development while also saving time and money. APIs provide flexibility, simplify design, administration, and use, and provide opportunities for innovation when creating new tools and products or managing existing ones.
Read Also: How to map array of objects in ReactJS?
Fetching API
Fetch API through fetch () method allows us to make an HTTP request to the backend.
” fetch ( url, options) ” where options refers to method i.e., GET or POST. By default, it is set to GET. We use the useEffect hook while requesting data from the endpoint which returns a promise that is either resolve or reject.
After fetching, we must now resolve the response object to JSON format using the json () method from which we can resolve to get the actual data that we need.
export default function App() {
// ...
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/posts?_limit=8`)
.then((response) => response.json())
.then((actualData) => console.log(actualData))
})
.then((actualData) => {
setData(actualData);
setError(null);
})
.catch((err) => {
setError(err.message);
setData(null);
})
.finally(() => {
setLoading(false);
});
}, []);
Whenever an error occurs, we handle it in the catch section.
Another more elegant method to get data is by using the async/ await method. To use this syntax, we must call it inside the async function then, add await syntax in front of the function to wait until the promise settles with the result.
Along with these two methods, we have another way.
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch("https://reqres.in/api/users?page=2");
const jsonData = await response.json();
setUsers(jsonData.data);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
We use async/await with a try / catch / finally statement to catch errors and manage the loading state.
Axios is a popular JavaScript library that enables HTTP requests to be made from a web browser or a Node.js server. It provides a simple API for making requests and handling responses, and it supports a wide range of request methods such as GET, POST, PUT, DELETE, and others.
You can visit the official website through Axios (axios-http.com)
When retrieving data from Axios, you must first decide what type of HTTP request to make. A GET request, for example, would be used to retrieve data from a server, whereas a POST request would be used to submit data to a server.
You can use the Axios API to make the request once you’ve determined the type of request you need to make. For example, to make a GET request to retrieve data, you would use the following code:
axios.get('/api/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
In this example, the Axios get()
method is being used to send a GET request to the URL /api/data
. The then()
method is then used to handle the response, which is logged to the console. If there is an error, the catch()
method is used to handle the error.
In this method the data we receive doesn’t need to be parsed as it is already in the json format. The axios does this work by itself thus eliminating the need to manually do it. Hence, the data we fetch can be used directly.
const App = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const response = await axios.get('https://reqres.in/api/users?page=1');
setUsers(response.data.data);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
Using Axios provide the following advantages over traditional fetch API, which are listed bellow:
- When sending requests, it automatically signifies the data.
- Unlike the fetch api, Axios has better error handling where it can throw 400-500 error range.
Conclusion
Hence, here we learned about API and how to fetch it along with how to use Axios to perform the basic API requests GET, POST and DELETE.