DEV Community

loading...
Cover image for Using a REST API in react

Using a REST API in react

tkbraincodes profile image Tk-brainCodes Updated on ・4 min read

WHAT IS AN API

An API stands for an "Application Programming Interface". It allows communication between softwares and provides ways of sharing data between applications. The REST API stands for "Representational State Transfer".

REST API is a software architectural style that defines a set of constraints and allows communication with RESTful web service. The REST API uses the HTTP request method to access and use data.

API METHODS

Below are the REST API methods:

  • Get Method: As the name implies, it gets the data directly from the API.

  • Post Method: The post method is used to give back data collected from the application to the server or an API.

  • Put Method: This action is used to make changes and update a request.

  • Delete Method: This method is used to eradicate pieces of information or data that are not needed.

    For this article, we are using a free API to demonstrate how to use the API call in react.

PROJECT SETUP:

Run this code in your command prompt to create a new react app.
npx create-react-app api-usage
then cd into the app:
cd api-usage
run yarn start or npm start
yarn start
npm start

You should see the react logo spinning in your browser

alt text

API FOR THIS PROJECT:

link to api: icanhazdadjoke.com

In this project, we are going to use Axios. Axios is used for making HTTP requests and used for fetching data from an API or a database or XMLRequests.
Run: npm i axios

Inside your App.js get rid of everything and it should look like this:

import React from 'react';
import './App.css';

function App() {

  return (
    <div className="App">
         {/*No component yet*/}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Then inside the src folder create a new component Joke.js.Since we installed Axios earlier we are going to import it into our app.

import React from 'react';
import axios from 'axios';

const Joke = () => {
return (
   <div>
      <h1>Jokes:</h1>
</div>
);
}
export default Joke;
Enter fullscreen mode Exit fullscreen mode

From the code above:

We are creating a new Joke component and rendering an h1, then we export the Joke component by default.

Next, we import the Joke component into the App.js component so that it can be displayed in the browser.

import React from 'react';
import Joke from './Joke';
import './App.css';

function App() {

  return (
    <div className="App">
         {/*Joke component*/}
           <Joke/>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In your browser, you should see Joke: displaying on the screen:

joke-image

Next, I am going to show how to use the API in our code.

import React, {useState} from 'react';
import axios from 'axios';

function Joke = () => {
     //create a state to store the jokes from the api
const [joke, setJoke]  useState([]); //make sure you to import useState from react

//store the api in a variable
    const apiLink = "https://icanhazdadjoke.com/";

//create a function to fetch the data
 const fetchData = async () => {
        const res = await axios.get(`${apiLink}`, { headers: { Accept: "application/json" } });
        console.log(res.data);
        console.log(res.data.joke)
    }

return (
   <div>
      <h1>Jokes:</h1>
</div>
);
}
export default Joke;
Enter fullscreen mode Exit fullscreen mode

From the code above:

I created a state const [joke, setJoke] = useState([])
to store the data from the api and created a function fetchData
to fetch data from the api that was stored in the variable
const apiLink = "https://icanhazdadjoke.com/"; then created the response variable const res = await axios.get(${apiLink}, { headers: { Accept: "application/json" } }).
We use async and await to wait for the data any time it fetches it. We also logged the data to the browser console so we can see what we fetched from the API. If you open your browser console by pressing f12 you will see the data from the API in an object {data}.

Next we are going to be displaying the jokes inside our browser.
Let's go 🚀🚀🚀...

//imports ....

const Joke = () => {
    const [joke, setJokes] = useState([]);


    const apiLink = "https://icanhazdadjoke.com/";

    const fetchData = async () => {
        const res = await axios.get(`${apiLink}`, { headers: { Accept: "application/json" } });
        console.log(res.data.joke);
        setJokes([res.data.joke]);
    }
    return (
        <div className="joke__">
            <h1>Jokes:</h1>
               {/*Fetch data from url*/}
                <button onClick={fetchData}>Load jokes</button>

                     {/*data from api goes here*/}
                    {joke && joke.map((j, index) => (
                         <div className="data" key={index}>
                          {j}
                         </div>
                     ))}
        </div>
    )
}

export default Joke;
Enter fullscreen mode Exit fullscreen mode

From the code above:

In the fetchData function, we set the state to the response of every joke we get from the API setJokes([res.data.joke]);.In the return statement we passed in the fetchData function to a button, for any time we click the button it loads new jokes <button onClick={fetchData}>Load jokes</button>.

From the code below:

We are mapping through the joke array if there is any joke, and returning the joke from the API in a div.

  {/*data from api goes here*/}
                    {joke && joke.map((j, index) => (
                         <div className="data" key={index}>
                          {j}
                         </div>
                     ))}
Enter fullscreen mode Exit fullscreen mode

Now start your app you would see Joke: and Load jokes displaying. When you click on the Load jokes button new jokes are displayed. It should look like this:

final-view

Summary:

In this article, we have seen how to use a REST API in react. By using the GET method to get data from the API icanhazdadjoke.com in JSON format then incorporating that data into our application.

You can reach out to me on Twitter @tkworldclass😉

Discussion (8)

pic
Editor guide
Collapse
petrtcoi profile image
Peter Tcoi

Hi. Is it better to use custom hook useJokes to hide all API logic from React Component? In this case you can change the source of jokes but no changes in the component.

Collapse
tkbraincodes profile image
Tk-brainCodes Author

Yes, you can, it works fine.

Collapse
jwhubert91 profile image
James Hubert

Great API! Love the jokes site.

Collapse
tkbraincodes profile image
Collapse
lukeshiru profile image
▲ LUKE知る

Have you tried react-query? Is a quite popular and well tested library to interact with APIs from React ✨

Collapse
tkbraincodes profile image
Tk-brainCodes Author

Alright, I will try it out.

Collapse
mikitashah profile image
mikitashah

Interesting, thanks for sharing! I have lately started working on react! This will be helpful!

Collapse
tkbraincodes profile image