DEV Community

talent
talent

Posted on

4 ways of calling an API in Javascript.

Which one do you think is the best?

Image description

Top comments (6)

Collapse
 
leob profile image
leob

I think all of them are incredibly similar, so I think it primarily depends on what else you're already using in your app/site.

For instance, if you're already using jQuery for other stuff, then just use jQuery $.ajax, rather than including yet another lib (like Axios etcetera).

If you're not using jQuery but "Vanilla JS" with a somewhat modern browser, then you might prefer "fetch" as it's natively supported by the browser (again, no need to load/include another lib).

Axios is a bit easier to use than "fetch", with way more baked-in features (which are however not that hard to emulate with "fetch") ... "fetch" is a little bit more low-level than Axios - but, Axios comes with a bundle size of 5KB gzipped.

XMLHttpRequest is a bit old-fashioned, "fetch" is its more modern and easier to use replacement.

So I think in most cases the choice would be between Axios and "fetch" (unless you happen to use jQuery).

Collapse
 
brense profile image
Rense Bakker

jQuery should disappear soon hopefully so don't use that. XML http request is cute, so don't use that.That leaves fetch api or axios. Both work cross platform now. Btw, there are more libs available for http requests like superagent. Axios is by far the most popular though, infact its one of the most popular libraries in the whole npm ecosystem.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

The title of this should really be "4 ways of making web requests in Javascript"

Collapse
 
talenttinaapi profile image
talent

Thanks Jon, for some of us english is not our native language

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

I don't think English is the issue here - your title is fine in that respect. An API doesn't necessarily reside on the web, and utilising one may not even involve making a web request.

Collapse
 
lukyncze profile image
Lukáš Sukeník

async await