DEV Community

Cover image for API Calls
Buddhadeb Chhetri
Buddhadeb Chhetri

Posted on

 

API Calls

Javascript API Calls

XML HTTP Request

  • All modern browsers support the XMLHttpRequest object to request data from a server.
  • It works on the oldest browsers as well as on new ones.
  • It was deprecated in ES6 but is still widely used.
var request = new XMLHttpRequest();
request.open('GET','https://jsonplaceholder.typicode.com/users')
request.send();
request.onload =() =>{
console.log(JSON.parse(request.response));
}
Enter fullscreen mode Exit fullscreen mode

Fetch API

  • The Fetch API provides an interface for fetching resources including across the network in an asynchronous.
  • It returns a Promise.
  • It is an object which contains a single value either a Response or an Error that occurred.
  • .then() tells the program what to do once Promise is completed.
fetch('https://jsonplaceholder.typicode.com/users')
.then(response=>{
return response.json();})
.then(data=>{
console.log(data);
})
Enter fullscreen mode Exit fullscreen mode

Axios

  • It is an open-source library for making HTTP requests.
  • It works on both Browsers and Node js.
  • It can be included in an HTML file by using an external CDN.
  • It also returns promises like fetch API
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

axios.get('https://jsonplaceholder.typicode.com/users')
.then(response =>{
console.log(response.data)})
Enter fullscreen mode Exit fullscreen mode

JQuery AJAX

  • It performs asynchronous HTTP requests.
  • Uses $.ajax() method to make the requests.
  • Ability to send GET and POST requests
  • Ability to Load JSON, XML, HTML or Scripts
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

$(document).ready(function(){
$.ajax({
url:"https://jsonplaceholder.typicode.com/users",
type:"GET",success:function(result){
console.log(result);
}
   })
})
Enter fullscreen mode Exit fullscreen mode

Rubico

  • asynchronous code should be simple.
  • functional style should not care about async.
  • functional transformations should be composable, performant, and simple to express.
const { pipe, map } = rubico

const toTodosUrl = id => `https://jsonplaceholder.typicode.com/todos/${id}`

const logTodoByID = pipe([ // fetch a Todo and log it
  toTodosUrl,
  fetch,
  response => response.json(),
  console.log,
])

const todoIDs = [1, 2, 3, 4, 5]

map(logTodoByID)(todoIDs) 
// fetch Todos per id of TodoIDs and log them
// { userId: 1, id: 4, title: 'et porro tempora', completed: true }
// { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
// { userId: 1, id: 3, title: 'fugiat veniam minus', completed: false }
// { userId: 1, id: 2, title: 'quis ut nam facilis...', completed: false }
// { userId: 1, id: 5, title: 'laboriosam mollitia...', completed: false }

// same as above but with limited concurrency
// map.pool(2, logTodoByID)(todoIDs)
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
lukeshiru profile image
Luke Shiru

Worth mentioning that the features you listed for jQuery, are present on all the previous approaches, is not only present in jQuery (one of many reasons people no longer use jQuery nowadays). XMLHttpRequest is the oldest one, and the most discouraged, mainly because afaik fetch is missing only on unsupported browsers, so if they no longer have support, you shouldn't support them either 😄

Cheers!

Collapse
 
buddhadebchhetri profile image
Buddhadeb Chhetri

Thank you for sharing your point of view.

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Sadly no fetch on IE11 (which I have 15% of my users on still, try getting old non-tech corporates to move). Next year, maybe...

Collapse
 
lukeshiru profile image
Luke Shiru

Luckily there are some pretty descent polyfills that you can load only for your IE users, instead of doing XHR manually, but still that sucks, hope your situation improves next year ☺️

Thread Thread
 
miketalbot profile image
Mike Talbot ⭐

Yeah polyfilled without a problem with a 4.5MB bigger bundle for IE11 lol with all the other stuff...

Collapse
 
artydev profile image
artydev

Great thank you.

You can add rubico rubico

const { pipe, map } = rubico

const toTodosUrl = id => `https://jsonplaceholder.typicode.com/todos/${id}`

const logTodoByID = pipe([ // fetch a Todo and log it
  toTodosUrl,
  fetch,
  response => response.json(),
  console.log,
])

const todoIDs = [1, 2, 3, 4, 5]

map(logTodoByID)(todoIDs) // fetch Todos per id of TodoIDs and log them
// { userId: 1, id: 4, title: 'et porro tempora', completed: true }
// { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
// { userId: 1, id: 3, title: 'fugiat veniam minus', completed: false }
// { userId: 1, id: 2, title: 'quis ut nam facilis...', completed: false }
// { userId: 1, id: 5, title: 'laboriosam mollitia...', completed: false }

// same as above but with limited concurrency
// map.pool(2, logTodoByID)(todoIDs)
Enter fullscreen mode Exit fullscreen mode

Regards

Collapse
 
buddhadebchhetri profile image
Buddhadeb Chhetri

yeah sure. thanks for your suggestion.

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post