How to fetch data from server with API and network request
Error Handling in async-await Using async-await How to use Fetch API? Features of Fetch API What is Fetch API? What are APIs? What are Network request
Overview
In modern Javascript, Network requests and APIs are fundamental. It makes a great role in data transferring. A developer should know network requests and APIs, and who wants to retrieve data from the server.
The Fetch API is now widely used in modern web development and has helped to streamline the process of making network requests and processing responses in Javascript.
What are Network requests?
The network request is often used to retrieve data from a server, such as HTML pages, images, or other resources, or to send data to the server, such as form submission or user input.
A network request is a process of sending a message from a client(usually a web browser) to a server and receiving a response.
What are APIs?
APIs(Application Programming Interfaces) are interfaces that define how software components should interact with each other.
In the context of web development, an API is typically a set of rules and protocols that enable a client to interact with a server and retrieve or manipulate data. This data can be in various formats, such as JSON or XML, and is often used to create dynamic and interactive web applications.
What is Fetch API?
The Fetch API is part of a web standard effort to modernize and simplify web development. It makes a more flexible and powerful way to make network requests in Javascript. Before the Fetch API, developers primarily used the XMLHttpRequest (XHR) API to make network requests. However, XHR had some limitations so it was replaced by Fetch API.
It uses a promise-based syntax and it is a more flexible request and response API. Fetch API provides a simpler and more powerful way to make network requests.
Features of Fetch API
Here are the features of the Fetch API.
Simple and more intuitive syntax:
The Fetch API uses a simpler and more intuitive syntax, with a promise-based API that makes it easier to work with asynchronous data.
Better support for new features:
The Fetch API is designed to support newer web features, which are not well-supported by earlier network requests.
Improved error handling:
The Fetch API provides better error handling, with clear and consistent error messages that are easier to understand and troubleshoot.
Request and response objects:
The Fetch API provides a request object that represents the request being made and a response object that represents the response returned by the server.
How to use Fetch API?
The Fetch API is used to call the fetch( ) method on the client side.
The fetch( ) method is not available by default in Node.js, to use the fetch() method in a Node.js application, we need to install the node-fetch package using npm.
Syntax
fetch("URL") //URL of the API end-point
.then((response) => response.json( ))
.then((data) => console.log(data));
Parameter
The fetch( ) method requires one parameter, the URL to request.
Return value
The fetch( ) method returns a promise object.
Example
Let's look at an example where we will use the fetch( ) method to get quotes from an open-source API.
We will use the URL "type.fit/api/quotes" as the API endpoint. The API endpoint returns an array of inspirational quotes and their authors.
Let's print the quotes onto the console.
Output:
The code fetches data from the quotes API using the fetch method, which returns a Promise. The response from the API is converted to JSON format using response.json() method, which also returns a Promise. The data returned from the API is then logged to the console using the console.log() method.
Using async-await
Output:
The code is fetch data from the quotes API using the async/await syntax in Javascript.
The fetchData() function is defined as an asynchronous function, which means it uses the await keyword to wait for a Promise to resolve before continuing with the next line of code. The fetch() method is used to request the API, and the response is saved to the response variable using the await keyword in the function.
Then, the response is parsed as JSON using the response.json() method and saved to the data variable using the await keyword. Finally, the resulting data is logged to the console using console.log().
Error Handling in async-await
Output:
The above code is using async/await with try-catch syntax error handling.
We have fetched an invalid URL in the fetch() method.
The getQuotes() function starts with a try block, within which the fetch() method is used to request the API, and the response is saved to the response variable using the await keyword. Then, the response is parsed as JSON using the response.json() method and saved to the data variable using the await keyword. Finally, the resulting data is logged onto the console.
If an error occurs during this process, it is caught by the catch block, and the error message is logged to the console. You can see the error in the console because we have fetched an invalid URL to the fetch() method.
And then, the finally block is executed, and a message is logged to the console indicating that the API request is closed.