Call a REST API in React
How to call a REST API using React in 10 minutes ๐
Introduction
In this tutorial we will guide you through how to call a REST API in React. To get everyone on board we will start with a fresh install of React but the principle for an existing app will be the same. If you want to skip ahead to the API call go to the Calling the API โ๏ธ section. In this example we are using a fake JSON REST API created using Mocki. You can read more about using Mocki to create mock APIs here. If you are using your own API you can replace the URL in the examples with your own API URL.
Project Setup ๐ฑ
To get a clean React app that we can use to interact with the API let’s use create-react-app
to get started as quickly as possible. To do this make sure you have npm
available in your command line.
Run the following command in your terminal to generate a starter app:
npx create-react-app my-app
This will create a React app in the directory my-app.
User Input ๐ฑ๏ธ
Usually when calling an API from your app you will do it based on the user input. In this case we will create a button that when pressed will trigger a call to the API.
If you successfully set your project up as in the first step we can create a button and a placeholder function in the file src/App.js
like this:
import React from 'react';
import './App.css';
function callApi() {
alert('Button was pressed!');
}
function App() {
return (
<div className="App">
<header className="App-header">
<button onClick={callApi}>Call API</button>
</header>
</div>
);
}
export default App;
This will give us a button that when pressed will show an alert saying Button was pressed!
. In the next step we will replace this alert with actually calling the API and displaying the data.
Calling the API โ๏ธ
To call the API we will use the built in fetch
library. This is widely supported by modern browsers and it is quite easy to use.
In our case we want to make a GET
request to the API. This is usually used to fetch data from the server. If you want to use another method such as POST
, PUT
, PATCH
or DELETE
you simply change the arguments passed in to the fetch function.
Let’s replace the code inside the callApi()
function with some real code:
function callApi() {
fetch('http://localhost:3001/fake', { method: 'GET' })
.then(data => data.json()) // Parsing the data into a JavaScript object
.then(json => alert(JSON.stringify(json))) // Displaying the stringified data in an alert popup
}
When you go to your app the data from the API will display in an alert popup after pressing the button.
Note: In this example we are assuming that the API will only return data in a JSON format.
Passing Parameters to the API ๐
Making a GET
request is quite simple. Let’s add some data to the API request. There are many types of data that you can pass in a HTTP request so let’s take a closer look at how it can look.
The fetch
library takes a number of arguments to pass this data.
This is an example:
fetch('https://myapi.com', { method: 'POST', headers: { accept: 'application/json', body: JSON.stringify({ message: 'Hello World!' }) } })
method
defines which HTTP method we are using (POST
,PUT
,PATCH
,DELETE
orGET
)headers
defines the headers for the request. Here we have added anaccept
header that tells the server that we want to get the response data inapplication/json
format.body
defines the body data that we want to send to the server. Typically you would pass data in the body when you want to store some sort of user input.
Another way to pass data to the server is query parameters. They are typically used with GET
requests and look like this when used in fetch:
fetch('https://myapi.com?message=hello', { method: 'GET' } )
The query parameter message
will in this case equal hello
.
Parsing the Response ๐ฆ
So far we have only displayed the body data from the response. Let’s dive a little deeper into how we can parse response data such as body values, headers and status codes.
Body Values
To get a specific body property from the response we can modify the callApi()
function to get the firstName property as follows:
function callApi() {
fetch('http://localhost:3001/fake', { method: 'GET' })
.then(response => response.json())
.then(data => alert(data.firstName) ) // Displays the firstName from the API response
}
Headers
To get a header value from the response we can modify the callApi()
function to get the content-type
header as follows:
function callApi() {
fetch('http://localhost:3001/fake', { method: 'GET' })
.then(response => alert(response.headers.get('content-type')))
}
Status Code
To get the status code returned by the request we can modify the callApi()
function as follows:
function callApi() {
fetch('http://localhost:3001/fake', { method: 'GET' })
.then(response => alert(response.status))
}
Conclusion ๐
Using the fetch
library to interact with a REST API is quite simple. Applying the skills that you have learned in this tutorial should get you ready to complete most API operations using a REST API.
Happy hacking!