WF Save it Lah
4 ways to make an
API Callin JS
2) @coder_aishya aOl
JavaScript 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
¢ Using Axios library
Cue] -la a WT-W4
@ @coder_aishya aoy)
XML HTTP Request
var XMLRequest = new XMLHttpRequest();
OTT eto alt De Re TL eA ee cele Re Bd
XMLRequest.send();
XMLRequest.onload = () => {
if (XMLRequest.status === 200) {
Cone Gretta ee orth a
pee EG
console.log("Error occurred!")
a
Cee MC OO MG ec eet ee eB)
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.
Still, it is used when we work with older browsers.
@ @coder_aishya =]03
Fetch API
fetch( 'https://api.github.com/users/coderaishya' )
.then(response => return response. json())
.then(data => {
console. log(data);
2)
a a eta
sever aes
Do checkout my post on
Fetch api guide to know more e)
in depth
Fetch API
Ultimate Guide
PA reer r)
@ @coder_aishya a(ey
Axios
¢ Axios is open-source library for making HTTP requests
with several great features.
¢ 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.
Axios Installation
Using Package Manager
ne DoD
VT ai melee D ated
and include it in the HTML file like
Sg a gee) (MLL eC Lee ake Ee Ree La hd
@ @coder_aishya a05
Using CDN
Pe eee at eM CM Cy, hee ea ee ae CeO
Seat ohed
axios.get("https://api.github.com/users/coderaishya" )
.then(response => {
console. log(response.data);
})
.catch(error => {
console. log(error);
2)
Sato need
Pros of Axios:
e Better and easier error handling & has a wide range
of browser support.
e Axios automatically perform JSON parsing and
returns data in JSON format.
2) @coder_aishya a06
jQuery AJAX
Attach jQuery inside Html file using CDN
Sema
sre="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min. js"
Peat
‘x Oe)
Pda tsed
$(document).ready(function () {
Een Eas
url: “https://api.github.com/users/coderaishya",
a7 FC
success: function (result) {
console. log(result);
oa
error: function (error) {
console, Log(error);
+
})
#)
) @coder_aishya aOy)
« Uses $.ajax() method to make the requests.
* the $.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.
AQ) @coder_aishya 7Did you find this post Useful ?
(3 Aishwarya | Front end Developer
as @coder_aishya