Explain Codes LogoExplain Codes Logo

How to call a REST web service API from JavaScript?

javascript
async-await
fetch-api
error-handling
Anton ShumikhinbyAnton Shumikhin·Dec 23, 2024
TLDR

Want to engage a REST API from JavaScript? Use fetch. For a quick GET request:

fetch('https://api.chromeIsBetter.com/humour') .then(res => res.json()) // Serve me JSON, please! .then(data => console.log(data)) // *Delicious data appears* .catch(err => console.error('Error:', err)); //*sad HTTP error noises*

To perform a POST request, set the method to 'POST'. Don't forget to include headers and the body of your request:

fetch('https://api.chromeIsBetter.com/postAConfession', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ confession: 'I once unvoted a SO answer.' }) }) .then(res => res.json()) // Got the response, decoding... .then(data => console.log(data)) // So, they know now... .catch(err => console.error('Error:', err)); // I forgot about CORS! Damn it!

Replace the URL and payload with your RESTful service details. Use .then() to deal with responses and .catch() to handle errors.

Async & await: Simplicity meets asynchronous

With asynchronous methods, using async and await keeps the code more readable. Here's a little makeover using them with fetch:

async function fetchMemes() { try { const res = await fetch('https://api.chromeIsBetter.com/memes'); const memes = await res.json(); // Fetching the memes console.log(memes); // A meme a day keeps the bugs away } catch (err) { console.error('Error:', err); // Something went wrong. No memes today folks. :( } } fetchMemes();

This syntax touch-up with async/await promises (pun intended) cleaner coding and graceful error handling.

More HTTP verb action with Fetch!

Fetch is no one-trick pony. Apart from GET and POST, here's a DELETE request

async function dustThanos() { try { const res = await fetch('https://api.marvel.com/thanos', { method: 'DELETE' }); console.log('Thanos dusted:', res.ok); // reject if not okay } catch (err) { console.error('Error:', err) // Thanos: "You should aim for the head." } } dustThanos();

Similar patterns can be used for the PUT, PATCH methods, with adjustments for headers and body based on your specific needs.

Not all heroes wear CORS

CORS issues can pop up and ruin the party. Adding suitable headers both for CORS and authorization requirements, can help address this:

fetch('https://api.chromeIsBetter.com/protected-content', { headers: { 'Content-Type': 'application/json', 'Authorization': 'FalsyAuthToken' } }) .then(res => res.json()) // Check check, 1, 2, 1, 2 .then(data => console.log(data)) // Yay! Stuff to do! .catch(err => console.error(err)); // Got rejected, duh!

This should work like a charm. Remember to refer to the API documentation to pick the right headers.

Error handling: Catching 'em all!

Error handling is as crucial as a catch in a game of baseball. Here are a few pointers:

  • Check the response status:
fetch('https://api.chromeIsBetter.com/bug-free-zone') .then(res => { if (!res.ok) { throw new Error('Oops! HTTP got cranky: ' + res.statusText); } return res.json(); }) .then(data => console.log(data)) // Phew, all good! .catch(err => console.error('Error:', err)); // Damn it, Error-201! Not again!
  • Judiciously handle errors in .catch() handler or use try...catch with async/await for even better error handling.

Alternatives to Fetch - XMLHttpRequest and jQuery

Before fetch became the cool kid, XMLHttpRequest was the go-to. Here's a simple GET request:

var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.chromeIsBetter.com/oldSchool', true); xhr.onload = function() { // Who knew we could still get a track list from a CD! }; xhr.send();

And we also have jQuery, simplifying AJAX to 'write less, do more':

$.ajax({ url: 'https://api.chromeIsBetter.com/getStuff', type: 'GET', success: function(data) { console.log(data); // jQuery, making lives easier since '06. }, error: function(err) { console.error('Error:', err); // Whoops! Tripped over a bug! } });

While fetch has been a game-changer, XMLHttpRequest and jQuery still have a sizeable following. It's always handy to know your way around these for broader application support and maintaining legacy codebases.

Tackling common API woes

Interacting with APIs can be tricky. Here's how to tackle common issues:

  1. Rate limiting (429 Too Many Requests): Implement a Retry-After header.
  2. Token expiration: Refresh the authentication tokens periodically to keep the session alive.
  3. Parsing errors: JSON.parse() the response to transform it to a JavaScript object. On error, reject the promise.
  4. Debugger: Use console.log() wisely to inspect responses and request data for better understanding of data received.