Through APIs, you are able to integrate pieces of software into your application without the nitty-gritty work. This process of using an API in your application is generally referred to as consuming an API. For instance, if you want to display a certain location on your website, you would use the Google Maps API instead of implementing the map functionality from scratch. APIs, therefore, reduce your workload and save you time.
To learn how to consume REST APIs in React using Fetch and Axios, you will build a simple React application that gets a random fact about cats from an API when you click a button.
Types of APIs
APIs can be classified by either availability or use case. In terms of availability, APIs can be public, private, partner, or composite APIs. When classified according to their purpose, they can be database, remote, operating systems, or web APIs. In this article, we will be consuming a type of web API called a REST (Representational State) API.
REST APIs allow you to get data from a source through a URL. In React, there are several methods you can use to consume REST APIs. This article discusses the two most popular methods namely the JavaScript Fetch API and the promise-based HTTP client Axios.
Prerequisites
To follow along with this guide, you should have:
Basic understanding of JavaScript. Basic knowledge of React, and React hooks. NPM installed locally on your machine. A text editor or IDE of your choice installed.
Create a React Application
First, you will need to create a React application. Copy the following command in your terminal to set up a React development environment.
Once the command completes executing, open the catfact folder in your text editor. You will be writing your code in the App.js file in the src folder so go ahead and remove the unnecessary code.
Next, create a simple UI that will use to display the random cat fact.
In app.js
To style your app, add the following code to the app.css file.
Your application should now look like this.
In the next steps, you will fetch data from the API and display it in the application.
Consuming REST APIs Using Fetch
Fetch API is an interface that allows you to get resources from an API through HTTP requests. The fetch() method receives the URL of the path to the resource as a mandatory argument and returns a promise that can resolve to a response.
The basic syntax of the fetch() method is as follows:
Implementing Fetch API
In React, the Fetch API is used the same way it’s used in plain JavaScript.
In the first line in the code above, you are passing in the API URL to the fetch() method. fetch() returns an HTTP response which is converted to JSON using the json() method. In the third line, you get access to the data which you can then use in the application. Finally, the catch block allows you to handle errors gracefully.
To implement the fetch request in the app component, you will use React hooks. By using the useEffect hook, your application will make the request once the component loads and the useState hook will create and update the state of the component. Keeping track of state ensures that the component re-renders when the fetch API returns the response.
Create a state to hold the cat fact and the function to update it.
Next, create a function to make the GET request to the API and call it in the useEffect hook.
Your app.js file should now look like this:
You should now be able to see a random fact about cats displayed in your browser.
Next, write code to display a random fact when the button is clicked.
Modify the button to include an onClick event and its handler function.
Define the handleClick() function as shown below.
Now, when you click the button, the handleClick() function will call fetchData() which will perform the API request and update the state with a new random fact. Consequently, the application UI will update to display the current fact.
Consuming REST APIs Using Axios
Instead of fetch(), you can consume APIs with Axios. Like fetch(), Axios allows you to make requests to an API endpoint. However, there are several differences between the two.
Axios automatically returns the response in JSON while you have to convert it to JSON when using the Fetch API. Axios requires only one . then() callback unlike the Fetch API. Axios is compatible with major browsers while Fetch is only supported in Chrome 42+, Edge 14 +, Firefox 39+, and Safari 10+
Implementing Axios
Install Axios by running the following command.
After the installation is completed, import the Axios package into your app component and modify the fetchFact() function to use it.
That’s it! Your application should be displaying a random cat fact when it loads in the browser and when you click the button.
More Uses for APIs With React
You can consume REST APIs in React using various methods. In this tutorial, you learned how to use Fetch and Axios to fetch a random fact from a REST API. The use cases of APIs in real world applications is endless.
For example, through payment APIs like Stripe and PayPal, stores can easily handle customer transactions online without needing to implement the functionality themselves. Therefore, even less technology savvy users can build useful applications that serve their needs.