Here are the possible ways to make an API call:
JSONPlaceholder is a free online REST API that you can use whenever you need fake data.
By default, we receive the response in a string format. We’ll need to parse it into JSON.
XMLHttpRequest was deprecated in ES 6 by the introduction of fetch. But XMLHttpRequest is still useful when you need to work with old browsers and don’t want polyfills.
Fetch allows you to make an HTTP request in a similar manner as XMLHttpRequest but with a straightforward interface by using promises. It’s not supported by old browsers (it can be polyfilled), but it’s very well supported among the modern ones. We can make an API call by using fetch in two ways.
Method 2: Async and Await
The fetch API is very powerful. We can easily send AJAX requests using the browser fetch API. The major disadvantage of fetch API is error handling.
It supports all modern browsers, including support for Internet Explorer 8 and higher.
How to Install Axios
Here’s how to install Axios if you are using any one of the package managers like npm or yarn.
Then include it in HTML file like this:
The easiest way to include Axios is by using external CDN:
Now you can start sending HTTP requests by including the following script in your HTML file.
Axios provides the following advantages:
- Axios performs automatic transformations and returns the data in JSON format.
- Better error handling.
- Axios has a wide range of supported browsers.
JQuery has many methods to handle asynchronous HTTP requests. In order to use jQuery, we need to include the source file of jQuery. The
$.ajax() method is used to make the HTTP request.
$.ajax method takes many parameters, some that are required and others that are optional. It contains two callback functions
error to handle the response received.
Most of the real-time applications use Axios to make HTTP requests. Axios is very easy to use and is an open-source library for making HTTP requests. And those are the most popular ways to make HTTP requests.