Greetings, devs! We’ll go through several approaches to calling an API for your upcoming project in this article.
XML HTTP Request
The XMLHttpRequest object is supported by all current browsers when requesting data from a server.
Both the newest and the oldest browsers are compatible with it.
Despite being obsolete in ES6, it is still commonly used.
var request = new XMLHttpRequest(); request.open('GET', 'https://api.github.com/users/karangor007'); request.send(); request.onload = ()=>{ console.log(JSON.parse(request.response)); }
Fetch
An asynchronous interface for resource retrieval, including network-wide resource retrieval, is provided by the Fetch API.
A Promise is returned.
It is an object that only has one value, either a Response or an error that happened.
The function.then() instructs the application on what to do when the Promise is fulfilled.
fetch('https://api.github.com/users/karangor007') .then(response =>{ return response.json(); }).then(data =>{ console.log(data); })
Axios
- An open-source HTTP request library is what it is.
- It is compatible with Node JS and browsers.
- It may be added via an outside CDN in an HTML file.
- It further yields promises like the fetch API.
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> axios.get('https://api.github.com/users/karangor007') .then(response =>{ console.log(response.data) }) </script>
jQuery – AJAX
- Asynchronous HTTP requests are made by it.
- makes the requests using the $.ajax() function.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $.ajax({ url: "https://api.github.com/users/karangor007", type: "GET", success: function(result){ console.log(result); } }) }) </script>
I appreciate your time. Together, let’s connect to learn and develop.