DEV Community

Cover image for Consume RESTful APIs like a Pro with axios and fetch()
jeetvora331
jeetvora331

Posted on

Consume RESTful APIs like a Pro with axios and fetch()

Hello there, fellow developers! Today, we're going to learn how to consume RESTful APIs like a pro using the awesome axios library and the native fetch() function. So, buckle up and let's dive into the world of APIs! 🚀

An API (Application Programming Interface) allows different software applications to communicate with each other. As a front-end developer, knowing how to consume data from an API is crucial because it gives your web app superpowers. It enables you to fetch data from external sources and display it on your website or manipulate it in any way you want.

Consuming APIs with fetch()

Fetch is a native browser API that makes it easy to fetch resources asynchronously. Let's see how we can use Fetch to consume a REST API.

const getData = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('An error occurred while fetching the data:', error);
  }
};

getData();
Enter fullscreen mode Exit fullscreen mode

Consuming APIs with axios

Axios is an NPM package for making HTTP requests in your apps. Axios is a promise-based HTTP client library that makes it easy to send asynchronous HTTP requests to REST endpoints. Let's see how we can use Axios to consume the same API in our React app.

First, we need to install Axios:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Now, let's make a GET request using Axios with async/await:

import axios from 'axios';

const getData = async () => {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    console.log(response.data);
  } catch (error) {
    console.error('An error occurred while fetching the data:', error);
  }
};

getData();

Enter fullscreen mode Exit fullscreen mode

And voilà! We've successfully fetched data from a REST API using Axios. 🎉

Fetch vs Axios: Which One to Choose?

Both Fetch and Axios are great for consuming RESTful APIs, but which one should you choose?

  • Fetch is a native browser API, while Axios is an external library.
  • Axios automatically converts the response to JSON, while Fetch requires an additional step.
  • Axios has better browser compatibility than Fetch. In general, it's advised to use Fetch for small applications and Axios for larger applications for scalability reasons

Congratulations! 🎉 You've learned how to consume RESTful APIs like a pro using both Fetch and Axios. Both methods have their advantages and use cases, so choose the one that best fits your needs and the size of your application. Now go out there and start consuming APIs like a pro! And remember, practice makes perfect. Happy coding! 😊

Top comments (0)