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)