React Js Consume REST API using Axios & Fetch Tutorial

React Axios and Fetch HTTP requests tutorial; This react tutorial will describe bits and pieces of how to consume REST API in React using Axios and Fetch.

If you have started your development journey recently with React js and want to amplify your knowledge, then this comprehensive guide is for you. We would like to address the very important concept of API consumption in React js since API is a well-known term in the software development field that makes subtle communication with the server to manage the data.

Axios is a handy package that allows making HTTP requests to a remote server to manage external resources. It gives you boundless freedom to retrieve, send, delete or update data over a network using the rest API with utmost precision.

Axios is a promise-based HTTP client exclusively built for the browser and node.js; the confluence of commemorative methods in Axios makes the communication with external resources facile. Methods such as get, post, delete, head, options, put, patch, and getUrl are the ultimate nector for making HTTP requests.

Fetch API is an ultimate prodigy that offers an amply clean way to get resources with the help of REST API with effect to make the asynchronous HTTP requests. Likewise, It profoundly supports CORS (Cross-Origin Resource Sharing).

How to Consume Rest API in React using Axios and Fetch

Here are the instructions that address consuming REST APIs in react with Axios and Fetch.

  • Step 1: Install New React Project
  • Step 1: Install Axios Package
  • Step 2: Create and Register Components
  • Step 3: Create Fake Backend Server
  • Step 4: Axios GET Request Example
  • Step 5: Fetch API POST Request Example
  • Step 6: Start React Application

Install New React Project

We assume you are ready to commence react development, so shake a lag and execute the provided command to install the new react app. However, if you are not new to react, ignore this step and move to the subsequent step.

npx create-react-app react-consume-rest-api-tutorial

Next, install the Bootstrap library in React to make the UI modules swiftly.

npm install bootstrap

Now, the bootstrap CSS has to be added in the src/App.js file, so follow the given instruction.

import React from 'react';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

function App() {
  return (
    <div className="App container mt-5">

    </div>
  );
}

export default App;

Install Axios Package

Axios carry weight in React application development; as far as HTTP requests are concerned, this package is a gold mine.

Run the recommended command to begin the installation of React Axios.

npm install axios

Create and Register Components

We aim to take you closer to reality as much as possible, so how about building a small to-do app that deals with only adding and showing to-do items.

So, without further ado, create the src/components folder and create todo_create.component.js and todo_list.component.js files within.

Formulate the new component template by adding the code in src/components/todo_create.component.js.

import React, { Component } from 'react';

export default class TodoCreateComponent extends Component {
    render() {
        return (
            <div>
                
            </div>
        )
    }
}

Update code in src/components/todo_list.component.js file.

import React, { Component } from 'react';

export default class TodoListComponent extends Component {
    render() {
        return (
            <div>
                
            </div>
        )
    }
}

Next, you require to plug in the todo components in the primary src/App.js file.

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';

import TodoCreateComponent from './components/todo_create.component';
import TodoListComponent from './components/todo_list.component';

function App() {
  return (
    <div className="App container mt-5">
       <TodoCreateComponent />
       <TodoListComponent />
    </div>
  );
}

export default App;

Create Fake Backend Server

If you have actual APIs, then use your own, but if you don’t have actual APIs, fret not; we will show you how to create a temporary fake server that similarly mocks like a real server. We are using a JSON server package to deal with APIs; on top of that, this plugin is insanely filled with notable virtues.

Run command to install the json server package.

npm install json-server

Let’s make it precisely manageable and head over to the root of your react project and create a new folder by the name of backend, also create a database.json file.

Next, pour below code into backend/database.json file, this is the logical archetype of your data that corresponds to HTTP calls.

{
    "todo": [{
        "id": 5,
        "title": "Buy a new gaming phone"
    }, {
        "id": 6,
        "title": "Learn how to play guitar"
    }, {
        "id": 7,
        "title": "Begin 5 km unstoppable running"
    }]
}

With the execution of the below command, start the API server.

json-server --watch backend/database.json --port 5555

Here is the basic APIs that you can use to communicate with the server through axios and fetch.

# Resources
  http://localhost:5555/todo

Axios GET Request Example

The following code snippet has the primary goal to significantly make the Axios HTTP POST request using the todo REST API.

Update code in. src/components/todo_create.component.js file.

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

export default class TodoCreateComponent extends Component {

    constructor(props) {
        super(props)

        this.onValChange = this.onValChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            title: '',
        }
    }

    onValChange(e) {
        this.setState({ title: e.target.value })
    }

    onSubmit(e) {
        const TASK = {
            title: this.state.title
        };

        axios.post('http://localhost:5555/todo/', TASK)
            .then((response) => {
                console.log(response.data)
            }).catch((error) => {
                console.log(error)
            });

        this.setState(
            { 
                title: '' 
            }
        )
    }


    render() {
        return (
            <div>
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label className="mb-2"><strong>Add Task</strong></label>
                        <input type="text" className="form-control" value={this.state.title} onChange={this.onValChange} />
                    </div>

                    <div className="d-grid mt-3">
                        <input type="submit" value="Submit" className="btn btn-primary" />
                    </div>
                </form>
            </div>
        )
    }
}

Fetch API POST Request Example

In this step, we will be showing you how to show the to-do list by making the HTTP request with fetch API; we will consume the JSON server API to accomplish this task.

Add code in. src/components/todo_list.component.js file.

import React, { Component } from 'react';


export default class TodoListComponent extends Component {

    constructor(props) {
        super(props)

        this.state = {
            todos: []
        };
      }
    
      componentDidMount() {
        const headers = { 'Content-Type': 'application/json' }

        const API = 'http://localhost:5555/todo';
        fetch(API, { headers })
            .then(res => res.json())
            .then((res) => {
                this.setState({ 
                    todos: res
                })
            });
    }

    render() {
        
        const { todos } = this.state;

        return (
            <ul className="list-group mt-4">
                {todos.map((res) => (
                    <li key={res.id} className="list-group-item list-group-item-info">
                        <span className="input-label">{res.title}</span>
                    </li>
                ))}
            </ul>
        )

    }
}

Start React Application

Let’s open the new terminal window and run the react development server using the following command, and yes, to view the app, use the printed url on the console screen.

npm start
http://localhost:3000/

Consume REST API with React Axios

Conclusion

Enough moving heaven and earth, we have eventually completed the React Axios REST API tutorial, not just that; we also found out how to use Fetch API in React to consume REST API easily. We are sure your discretion must be asking what is best, either fetch or Axios, which what should I reckon to lower down the excruciating pain of handling APIs.

Well, both Axios or Fetch both carries weight in terms of the requirement. If you build a large or enterprise-level application, then Axios can refrain you from getting into hot water, whereas smaller applications can easily be managed with fetch API.