4 ways to make an
API Callin JSJavaScript provides a few built-in methods and
external open source libraries to create and interact
with the API. A few possible methods to make an API
call in JavaScript are:
¢ XMLHttpRequest
¢ Fetch
e Using Axios library
e jQuery AJAXvar XMLRequest = new XMLHttpRequest();
Para
ea eee Le ee eT E
XMLRequest.send( );
SOS aT a oe
TOC CCL tse wen mG
CRMC corel ace a
bar ET f
console. log( "Error occurred!")
}
onsole. Log( JSON. parse( XMLRequest . response) )
¢ It receives response in string format that needs to be
parsed in JSON format
(JSON.parse(XMLRequest.response)).
¢ It is a built-in browser object to create HTTP requests &
is deprecated with the introduction of fetch in ES 6.03
Fetch API
fetch( 'https://api.github.com/users/coderaishya' )
.then(response => return response. json())
.then(data => {
console. log(data) ;
a)e Axios is open-source library for making HTTP requests
with several great features.
e Axios works in both Node.js and browsers and is a
promise-based (asynchronous) HTTP client, which
even is used in frameworks like Angular and React.
Using Package Manager
TS
yarn add axios
and include it in the HTML file like
Using CDN
ee
as ="https://unpkg.com/axios/dist/axios.min.js">
Lz)
{
i - log(error);
t)
Pros of Axios:
¢ Better and easier error handling & has a wide range
of browser support.
e Axios automatically perform JSON parsing and
returns data in JSON format.Attach jQuery inside Html file using CDN
Peat ts
re="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min. js"
>
Stat hed
$(document).ready(function () {
Eo BL Daas
url: “https://api.github.com/users/coderaishya",
type: "GET",
success: function (result) {
console. log( result);
H
Tage] een von Col Cl
console. Log(error);« Uses $.ajax() method to make the requests.
« the S.ajax() method takes several parameters, some
optional and some required. This method contains two
callback functions: success and error to handle the
received response easily.