DEV Community

Cover image for Better API Calls 🎣
Shivam Singh
Shivam Singh

Posted on • Updated on

Better API Calls 🎣

"Fetch!" Nope, we're not teaching your dog new tricks. πŸ• We're diving into the nitty-gritty of API calls in JavaScript. So buckle up, because if API calls were Pokemon, Fetch would be your Pikachuβ€”small, lovable, and shockingly powerful. ⚑

1️⃣ Fetch is So Fetch! 😎

Let's kick things off by asking the existential questionβ€”what the fetch is Fetch? Sorry, couldn't resist. Fetch is the cool kid in the school of API requests. While XMLHttpRequest sits in the corner listening to '80s music 🎢, Fetch is out there making async look easy.

fetch('https://dog.ceo/api/breeds/image/random')
  .then(response => response.json())
  .then(data => console.log(data.message));
// Output: A random dog image URL
Enter fullscreen mode Exit fullscreen mode

2️⃣ Get it Right with GET 🎯

By default, Fetch does a GET request. It gets data like my Aunt Gertrude gets catsβ€”quickly and a lot of them. Here's how to fetch like you've never fetched before.

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data));
// Output: JSON data of the first post
Enter fullscreen mode Exit fullscreen mode

3️⃣ POSTing Bills or POSTing Data? πŸ“«

Sure, you can GET all day, but what about when you want to send some data out into the wild blue yonder of the interwebs? That’s when POST comes to the rescue!

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({ title: 'Foo', body: 'Bar', userId: 1 }),
})
  .then(response => response.json())
  .then(data => console.log(data));
// Output: The new post's JSON data
Enter fullscreen mode Exit fullscreen mode

4️⃣ Error? I Barely Know Her! 🚫

When Fetch goes wrong, it doesn’t really scream and shout. Nope, it'll give you a 404 as calmly as a British butler. You have to catch errors like you're trying to juggle flaming torches.πŸ”₯

fetch('https://this.isnotarealwebsite.com')
  .catch(error => console.log('Oopsie daisy:', error));
// Output: Oopsie daisy: [error details]
Enter fullscreen mode Exit fullscreen mode

5️⃣ Headers: Not Just for Shampoo 🧴

In API calls, headers aren't above your eyes; they’re above your request. They tell the API what's going on, like a tour guide in a museum.

fetch('https://jsonplaceholder.typicode.com/posts', {
  headers: { 'Content-Type': 'application/json' },
})
  .then(response => response.json())
  .then(data => console.log(data));
// Output: All the posts, but like, professionally
Enter fullscreen mode Exit fullscreen mode

6️⃣ Abort! Abort! Cancel That Fetch! 🚨

So, what if you've sent off a Fetch request, but then you're like, "Eh, never mind"? Fear not, the AbortController is here, a superhero in the realm of JavaScript. This buddy can stop a Fetch operation faster than you can say "Oops!"

const controller = new AbortController();
const { signal } = controller;

fetch('https://dog.ceo/api/breeds/image/random', { signal })
  .catch(err => console.log('Fetch aborted:', err));

controller.abort();
// Output: Fetch aborted: AbortError: The operation was aborted.
Enter fullscreen mode Exit fullscreen mode

7️⃣ Fetching in Parallel: Because Time is Money, Honey! πŸ’Έ

Why fetch one thing when you can fetch ALL the things? Use Promise.all to fetch multiple things at once and laugh in the face of latency.

Promise.all([
  fetch('https://jsonplaceholder.typicode.com/posts/1'),
  fetch('https://jsonplaceholder.typicode.com/posts/2'),
])
  .then(responses => Promise.all(responses.map(res => res.json())))
  .then(data => console.log(data));
// Output: An array of JSON data for posts 1 and 2
Enter fullscreen mode Exit fullscreen mode

8️⃣ Fetched Data Transformation: From Zero to Hero πŸ’ͺ

Once you've got that Fetch response, it's not always perfect for your needs. You might need to do some data transformation to get it into shape. Let's get it from zero to hero!

fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
  return data.map(post => {
    return {id: post.id, title: post.title.toUpperCase()};
  });
})
.then(transformedData => console.log(transformedData));
// Output: An array of posts with all titles in uppercase!
Enter fullscreen mode Exit fullscreen mode

Conclusion πŸŽ‰

Alright, fam! We've learned how to fetch like there’s no tomorrow. So, let's all be fetchin' fantastic. Got more tips on API calls or stories about how you 'fetched' something up? Share them in the comments below! πŸŽ€β¬‡οΈ


Top comments (0)