React JS + Spring Boot REST API example tutorial

Posted by doddatika on Sun, 13 Feb 2022 03:02:28 +0100

In this tutorial, we will use React as the front end and Spring Boot as the back end to create a simple "single page application".

React is used to build a user interface (UI) at the front end.

Spring Boot is very popular in developing RESTful Web services and micro services.

As we all know, React is a JavaScript based library, which does not have the ability to send HTTP requests; Therefore, we need to use a third-party library to achieve this.

There are many libraries available for making HTTP calls to React applications. Some of these are listed below.

  • Axios
  • Fetch
  • Superagent
  • React-axios
  • Use-http
  • React-request

In this sample tutorial, we will use the Axios HTTP library to make HTTP Get REST API calls.

5. Conditions precedent

  • Basic familiarity with HTML & CSS
  • Basic knowledge of JavaScript and programming
  • Spring Boot Basics
  • ReactJS Basics
  • Install node globally JS and npm

What will we build?

We will build two projects:

  1. Sprint boot backend (server) – develop rest APIs
  2. React front (client) – use REST API

Client server architecture

1. Develop Spring Boot backend application

We will use Spring Data JPA Develop the repository layer and use H2 memory database to store data.

1. Create a Spring Boot application

There are many ways to create Spring Boot applications. You can refer to the following articles to create Spring Boot applications.

>> Create a Spring Boot project using Spring Initializer
>> Create Spring Boot project in Spring Tool Suite [STS]

2. Add maven dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.1.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.blogspot.javabyrajasekhar</groupId>
	<artifactId>SpringbootCommandLineRunner</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringbootCommandLineRunner</name>
	<description>SpringbootCommandLineRunner</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Create JPA entity - user java

On net javaguides. Create a new package named model in the springboot package, and then create the User class in the model package. Its contents are as follows-

package net.javaguides.springboot.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private long id;

	@Column(name = "first_name")
	private String firstName;

	@Column(name = "last_name")
	private String lastName;

	private String email;

	public User() {

	}

	public User(String firstName, String lastName, String email) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}

Create Spring Data JPA Repository - userrepository java

On net javaguides. Create a new package named repository in the springboot package, and then create the following interfaces in the repository package-

package net.javaguides.springboot.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import net.javaguides.springboot.model.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long>{

}

Spring controller with REST API - / api/users

Let's create a UserController class and add the following code to it:

package net.javaguides.springboot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import net.javaguides.springboot.model.User;
import net.javaguides.springboot.repository.UserRepository;

@CrossOrigin
@RestController
@RequestMapping("api/")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("users")
    public List < User > getUsers() {
        return this.userRepository.findAll();
    }
}

Please note that we added the following lines of code to avoid CORS problems:

@CrossOrigin(origins = "http://localhost:3000")

Run the Spring Boot application and test the Rest API

Let's insert a few records into the user table} when the application starts.

Let's run the Spring Boot application from the IDE - > right click - > run as - > java application:

package net.javaguides.springboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import net.javaguides.springboot.model.User;
import net.javaguides.springboot.repository.UserRepository;

@SpringBootApplication
public class SpringbootBackendApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootBackendApplication.class, args);
    }

    @Autowired
    private UserRepository userRepository;

    @Override
    public void run(String...args) throws Exception {
        this.userRepository.save(new User("Ramesh", "Fadatare", "ramesh@gmail.com"));
        this.userRepository.save(new User("Tom", "Cruise", "tom@gmail.com"));
        this.userRepository.save(new User("Tony", "Stark", "tony@gmail.com"));
    }
}

Click this in the browser " http://localhost:8080/api/users "Link takes the popular user list as JSON:

 
 

Build React JS front-end application

Let's continue to create a React application to use the / api/users # REST API.

1 - create a React UI using Create React App

The Create React App CLI tool is an officially supported way to create a single page React application. It provides a modern build setup without configuration.

To create a new application, you can choose one of the following methods:

Using npx

npx create-react-app react-frontend

Using npm

npm init react-app react-frontend

npm init is available in npm 6 +

Use yarn

yarn create react-app react-frontend

Running any of these commands creates a directory called react frontend in the current folder. In this directory, it will generate the initial project structure and install the pass through dependencies:

react-frontend
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│   ├── favicon.ico
│   ├── index.html
│   ├── logo192.png
│   ├── logo512.png
│   ├── manifest.json
│   └── robots.txt
└── src
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── index.css
    ├── index.js
    ├── logo.svg
    └── serviceWorker.js

Let's explore the important files and folders of the react project.

For the project to be built, these files must exist with the exact file name:

  • public/index.html # is a page template;
  • src/index.js is a JavaScript entry point.  

You can delete or rename other files} let's quickly explore the project structure.

package.json  -  package. The JSON} file contains all the dependencies required for our React JS project. Most importantly, you can check the current version of React you are using. It has all the scripts to launch, build and pop up our React application.

Public folders - public folders contain index html. Since react is used to build single page applications, we have an HTML file to render all our components. Basically, it is an HTML template. It has a div element with id as the root, and all our components are presented in this div, index HTML} as a single page that completely reflects the application.

src folder - in this folder, we have all the global javascript and CSS files. All the different components we're going to build sit here.

index.js - this is the top-level renderer for your react application.  

node_modules - all packages installed by NPM or Yan will reside on the node_modules folder.

App.js  -  App.js file contains the definition of our app # component, which is actually rendered in the browser. This is the root component.

2 - add a bootstrap in React using NPM

Open a new terminal window, navigate to the project folder, and then run the following command:

$ npm install bootstrap --save

After installing the bootstrap package, you need to import it into your React application entry file.

Open Src / index JS file and add the following code:

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

src/index.js

Here is the index Complete code of JS file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

3. React service component - REST API call

For our API calls, we will use} Axios. The following command is to install axiom.

npm add axios

The following is the userservice for HTTP REST call through Axios JS service implementation.  

Our backend user endpoint is located at http://localhost:8080/api/users.

import axios from 'axios'

const USERS_REST_API_URL = 'http://localhost:8080/api/users';

class UserService {

    getUsers(){
        return axios.get(USERS_REST_API_URL);
    }
}

export default new UserService();

Ensure that the object of the UserService class is created and exported as:

export default new UserService();

4. Develop a React component

Components are the building blocks of our entire React application. Like functions, they accept input from props and states, and output the UI presented in the browser. They are reusable and composable.

React components can be function components or class components. In this example, we will use class components.

Let's create a usercomponent JS file and add the following code to it.

import React from 'react';
import UserService from '../services/UserService';

class UserComponent extends React.Component {

    constructor(props){
        super(props)
        this.state = {
            users:[]
        }
    }

    componentDidMount(){
        UserService.getUsers().then((response) => {
            this.setState({ users: response.data})
        });
    }

    render (){
        return (
            <div>
                <h1 className = "text-center"> Users List</h1>
                <table className = "table table-striped">
                    <thead>
                        <tr>

                            <td> User Id</td>
                            <td> User First Name</td>
                            <td> User Last Name</td>
                            <td> User Email Id</td>
                        </tr>

                    </thead>
                    <tbody>
                        {
                            this.state.users.map(
                                user => 
                                <tr key = {user.id}>
                                     <td> {user.id}</td>   
                                     <td> {user.firstName}</td>   
                                     <td> {user.lastName}</td>   
                                     <td> {user.email}</td>   
                                </tr>
                            )
                        }

                    </tbody>
                </table>

            </div>

        )
    }
}

export default UserComponent

Let's understand the above code step by step.

  • constructor() - call the constructor() before installing the component. In the constructor, we declare state variables and bind different methods so that they can be accessed from the state inside the render() method.

  • componentDidMount() - componentDidMount() is called once the component is installed and ready.

  • render() - the render() method is the most commonly used lifecycle method. The render() method actually outputs HTML to the DOM.

We are using the map operator to traverse our user list and create the following view:

{
 this.state.users.map(
  user => 
  <tr key = {user.id}>
    <td> {user.id}</td>   
    <td> {user.firstName}</td>   
    <td> {user.lastName}</td>   
    <td> {user.email}</td>   
  </tr>
 )
}

5. Application js

In the previous step, we have created UserComponent, so let's continue to add UserComponent to App component:

import React from 'react';
import logo from './logo.svg';
import './App.css';
import UserComponent from './components/UserComponent';

function App() {
  return (
    <div className="App">
        <UserComponent />
    </div>
  );
}

export default App;

6. Operation reaction application

Start the project with the following command:

npm start

To start a project with yarn:

yarn start

Run the application in development mode. Open http://localhost:3000 View in browser.

conclusion

In this tutorial, we created a simple "single page application" using React as the front end spring boot  As the back end. We also saw how to use the Axios HTTP library to integrate the React front-end application with the Spring Boot back-end.

If you want to use React Hooks in React App, please check React JS (React Hooks) + Spring Boot tutorial 

Topics: Javascript React Spring Boot