DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • HTTP API: Key Skills for Smooth Integration and Operation (Part 1)
  • Unleashing the Power of GPT: A Comprehensive Guide To Implementing OpenAI’s GPT in ReactJS
  • How To Integrate the Stripe Payment Gateway Into a React Native Application
  • How To Build Web Service Using Spring Boot 2.x

Trending

  • Metrics at a Glance for Production Clusters
  • Data Quality: A Novel Perspective for 2025
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. API Integration with Axios in React

API Integration with Axios in React

In this article, we will learn how to consume a web service in our react application and use Axios as an HTTP client for making HTTP Requests

By 
Mrityunjay Karn user avatar
Mrityunjay Karn
·
Aug. 26, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
62.1K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will learn how to consume a web service in our react application. We are going to use Axios as an HTTP client for making HTTP Requests, so before dive in, let’s understand a little bit about Axios, its features, and how we can make HTTP requests using Axios.

Axios

Axios is a promise based HTTP client for making HTTP requests from a browser to any web server.

Features of Axios

  • Makes XMLHttpRequests from browser to web server
  • Makes HTTP request from node.js
  • Supports the promise API
  • Handles request and response
  • Cancel requests
  • Automatically transforms JSON data

Installation

Using npm

$ npm install axios -- save

Example of get and post request:

//post request

axios.post(‘/url’,{data:’data’}).then((res)=>{
//on success
}).catch((error)=>{
//on error
});

//get request

axios.get(‘/url’,{data:’data’}).then((res)=>{
//on success
}).catch((error)=>{
//on error
});

Performing multiple concurrent requests:

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

Using Axios in Our React Application

I am assuming that you have basic knowledge of react fundamentals and it’s life cycle methods.

Step 1: In order to make an HTTP request, we need to install Axios and add it’s dependency in our package.json file. If you have not already installed, then use this command in your terminal.

npm install axios --save

Step 2: In order to use Axios in our project, we need to import Axios from our node modules.

import axios from "axios";

Step 3: Now create a React component, where we want to consume any web service in our react application.

Here, we want to display user message suppose, so we make a component and initialize with initial state.

import React,{Component} from  ‘react’;

class UserMsg extends Component{
constructor(){
super();
this.state={
userMsg:null
}
}
render(){
return(
{
this.state.userMsg!=null &&
<div>
<h2>{this.state.userMsg.title}</h2>
<p>{this.state.userMsg.body}</p>
</div>
}
);
}
}  

export default UserMsg;

Step 4: Now make a rest call inside the componentDidMount method of react component lifecycle.

The componentDidMount is executed after the first render only on the client side. This is where AJAX requests and DOM or state updates should occur. This method is also used for integration with other JavaScript frameworks and any functions with delayed execution like setTimeout or setInterval. We are using it to update the state so we can trigger the other lifecycle methods.

We are making a get request with a public API "https://jsonplaceholder.typicode.com/posts/1"

That will return JSON

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
}

In the componentDidMount method, we make a REST API call and set the state to display on UI.

componentDidMount(){
axios.get(‘https://jsonplaceholder.typicode.com/posts/1’,{}).then((res)=>{
//on success
this.setState({
userMsg:res.data
});

}).catch((error)=>{
//on error
alert(“There is an error in API call.”);
});
}

Here is the output of the complete program:

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

class UserMsg extends Component{
constructor(){
super();
this.state={
userMsg:null
}
}
componentDidMount(){
axios.get("https://jsonplaceholder.typicode.com/posts/1",{}).then((res)=>{
//on success
this.setState({
userMsg:res.data
});

}).catch((error)=>{
//on error
alert("There is an error in API call.");
});
}

render(){
return(

this.state.userMsg!=null &&
<div>
<h2>{this.state.userMsg.title}</h2>
<p>{this.state.userMsg.body}</p>
</div>

);
}
}  

export default UserMsg;
API React (JavaScript library) Requests Integration Web Service

Published at DZone with permission of Mrityunjay Karn. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • HTTP API: Key Skills for Smooth Integration and Operation (Part 1)
  • Unleashing the Power of GPT: A Comprehensive Guide To Implementing OpenAI’s GPT in ReactJS
  • How To Integrate the Stripe Payment Gateway Into a React Native Application
  • How To Build Web Service Using Spring Boot 2.x

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!