Create REST CRUD API With SpringBoot & SpringData-JPA.
Tags: beginners, springboot, microservices, restapi
Published: 2021-06-10 18:22:53

Signed in as @priyankanandula 


Hurrah :smiley: , finally I started writing technical blogs to share my practical implementation knowledge in programming.
This is the My First Blog come let's start :heart_eyes:.


Hope you guys will definitely gain some knowledge after completion of reading this blog.

No delay let's start this :point_down:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/prnemw7zkaai8c5uigjx.png)

In this `blog`, you will learn how to develop **RESTful** web services APIs for **CRUD** operations on a **MySQL database**. The CRUD operations include _Create, Retrieve, Update and Delete_.

####Technologies & Tools Required.

+ Java Development Kit (JDK 1.8 or newer)
+ MySQL Database server (including MySQL Workbench and MySQL Command Line Client to manage database)
+ STS(Spring Tool Suite)--4.10.0.RELEASE for creating SpringBoot projects  
+ Postman (to test RESTful APIs)

--

> NOTE: You can use your favorite IDE like Eclipse, IntelliJ...



####Implementation Steps :


1. Creating SpringBoot Maven Project in STS.

2. Creating Database in Mysql in CommandLine

3. Creating a Table in Database using MySQL WorkBench UI.

4. Creating an Entity Class in Project

5. Creating a JPA Repository to perform CRUD Operations for Entity Class

6. Configure Data Source Properties

7. Creating a RestController Class for GET , POST, PUT ,UPDATE & DELETE HTTP Methods

8. Run our SpringBoot Application in Embedded Tomcat Server

9. Test our Restful services using Postman




_We will create  Final Project Structure  as below_
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/znjoeyghst8acmbq2dnz.png)

----- 

###1. Creating SpringBoot Maven Project in STS :

After open `STS` you can go through  _File ->New -> Spring Starter Project_

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/up9rvbju9io6uq2m4z2q.png)


####Provide the details as below:

  1.Name - any name as your wish (in this blog I gave as ProductRestAPI)

  2.Type - Maven

  3.Group, Artifact & Package - you can give any values as your wish.

> Here I have used...
    Group - com.priya.springweb
    Artifact - ProductRestAPI
    Package - com.priya.springweb


![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dl5z36r7ey8lwv5824wp.png)


*Click Next* and then select the following `dependencies` that are required and then click finish.


  > 1.The artifact **spring-boot-starter-web** is for Spring Web MVC, RESTful web services, and embedded Tomcat server.

  > 2.The artifact **spring-boot-starter-data-JPA** is for Spring Data JPA and Hibernate.

  > 3. The artifact **MySQL-connector-java** is for the JDBC driver for MySQL.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fybsgnm0p9bc04mnas01.png)
 
After `click finish`, the project gets created as below.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1c8gnw2ywrpzw5sgt1u4.png)

####Maven POM File:

```Java
<?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.5.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.priya.springweb</groupId>
	<artifactId>ProductRestAPI</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>ProductRestAPI</name>
	<description>Demo project for Spring BootRestAPI</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

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

</project>
```
-----

###2.Creating Database in Mysql in CommandLine 

Open _MySQL Commandlind Client_ and log in with the `password` you have given at the time of installation.

I have used _root user_.

Create a _database with any name_ in this I have used **myproducts**.


![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i9g2c72lr19g8deuzle8.png)


![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w643px3gwb0l7107t0dk.png)

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9m6tlqq6rrlb21u89xnn.png)

-----


###3.Creating a Table in Database using MySQL WorkBench

Execute the following _SQL script_ in `WorkBench`.  

```SQL
use myproducts;

create table product(
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
name varchar(20),
description varchar(100),
price int
);
```

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ogfh2ejxak8026x1dy3.png)

-----

###4.Creating an Entity Class in Project

Create a package like _com.priya.springweb.entities_ and then create the `Product` class to *map with the product table* in the database as follows:

```JAVA
package com.priya.springweb.entities;

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

@Entity
public class Product {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private int id;
	private String name;
	private String description;
	private int price;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	
}
```


We have used _@GeneratedValue(strategy=GenerationType.IDENTITY)_ because in the *Database table we mentioned the id column as Auto_Increment to get these auto-generated values from a database*.


> NOTE: This is a simple domain model class, *with class name and field names are identical to table name and column names in the database* – _so we can use the minimum number of JPA annotations_.

-----

###5.Creating a JPA Repository to perform CRUD Operations for Entity Class

To take advantages of `Spring Data JPA`, create the `ProductRepository` interface as below:

```JAVA
package com.priya.springweb.repos;

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

import com.priya.springweb.entities.Product;

public interface ProductRepository extends JpaRepository<Product, Integer> {

}
```

> NOTE : Here JpaRepository arguments represents _<EntityClassName,DataType of PrimaryKey>_

-----

###6.Configure Data Source Properties

In `main/resources/application. properties` file we need to specify _database-connection_ information as follows.

```java
spring.datasource.url=jdbc:mysql://localhost:3306/myproducts
spring.datasource.username=root
spring.datasource.password=root

server.servlet.context-path=/productapi
```


> Remember to update url, username and password according to your MySQL database server.


> NOTE:Here the context path is the name of the URL at which we access the application. The default context path is empty.you can provide any name here.

-----

###7.7.Creating a RestController Class for GET , POST, PUT ,UPDATE & DELETE HTTP Methods

Here, we come to the part that actually exposes _RESTful APIs_ for *CRUD* operations – a Spring controller following REST style. Create the `ProductController` class with some initial code as below:

```JAVA
package com.priya.springweb.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.priya.springweb.entities.Product;
import com.priya.springweb.repos.ProductRepository;

@RestController
public class ProductController {
	
	@Autowired
	private ProductRepository repository;

	@RequestMapping(value="/products",method=RequestMethod.GET)
	public List<Product> getProducts(){
		
		return repository.findAll();
	}
	
	@RequestMapping(value="/products/{id}",method=RequestMethod.GET)
	public Product getProductById(@PathVariable("id") int id) {
		
		return repository.findById(id).get();
		
	}
	
	@RequestMapping(value="/products/",method=RequestMethod.POST)
	public Product createProduct(@RequestBody Product product) {
		
		return repository.save(product);
	}
	
	
	@RequestMapping(value="/products/",method=RequestMethod.PUT)
	public Product updateProduct(@RequestBody Product product) {
		
		return repository.save(product);

	}
	
	@RequestMapping(value="/products/{id}",method=RequestMethod.DELETE)
	public void  deleteProduct(@PathVariable("id") int id) {
		
	repository.deleteById(id);
		
	}
}
```

     **@RestController** - The _@RestController_ annotation is used to define the RESTful web services. It serves JSON, XML and custom response

**@RequestMapping** - The _@RequestMapping_ annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET.

**@PathVariable** - The _@PathVariable_ annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {}

**@RequestBody** - The _@RequestBody_ annotation is used to define the request body content type.


> NOTE:You must use @ResponseBody for Update and Create operations.

-----

###8. Run the SpringBoot Application in Embedded Tomcat Server

_Right Click on your project and then select run as Spring boot app._

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/14mf0un6ggtya0ka3z77.png)

-----

###9. Testing our Restful services in Postman

######1. Create Product Details - `POST METHOD`

_URL_ : http://localhost:8080/productapi/products/ 


![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xz6felmgzfnyj40wi66q.png)

> NOTE : Here in body JSON _no need to pass id_ as it as already automatically generated by Database.
 
Must Select data type as JSON .

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mzdc7my83wqhl8w5fvip.png)

Yo :metal:! Data inserted successfully. Great Job. 

######2.Get Product Details - `GET METHOD`

   _URL_ - http://localhost:8080/productapi/products

#####Response :

```JSON
[
    {
        "id": 1,
        "name": "IPhone",
        "description": "Its Awesome Product",
        "price": 1000
    },
    {
        "id": 2,
        "name": "Mac Book Pro",
        "description": "Its Amazing Product",
        "price": 3000
    },
    {
        "id": 6,
        "name": "Ipad Airpods",
        "description": "It is Good  Product",
        "price": 10000
    },
    {
        "id": 7,
        "name": "Ipad Mini",
        "description": "It is Good  Product",
        "price": 7000
    }
]
```

> NOTE : No need to pass any body for GET.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fqsbc3hqcb2ne2o709c9.png)


######3. Get Product Details by ID - `GET METHOD`

_URL_ - http://localhost:8080/productapi/products/7 
 
  *Give any id of product that exists in Database Product table*.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fc5t1hfkeccra87z7ypf.png)


######4.Update Product Details  - `PUT METHOD`

_URL_ - http://localhost:8080/productapi/products/

```JSON
{
    "id": 7,
    "name": "Ipad Mini",
    "description": "It is Good  Product",
    "price": 10000
}
```
 
`Here I am updating the price to 10000 earlier we have given 7000`.

> NOTE : You must mention all the fields for PUT Method based upon the Id it wil lupdate the details in database table

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/volhtcgvo7tp6ry41v93.png)



######5. 5.Delete Product Details by Id - `DELETE METHOD`


_URL_ -  http://localhost:8080/productapi/products/7  


![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mprfpt2novy9yy4s0vpm.png)


 ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ze64mp5b1htw86k3mr2a.png)




_It deleted the Product successfully_ . 



---------------------

Thats it guys,WOW :grinning: Good Job .We have completed creating REST API CRUD in Spring Boot.


![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/90qcvy3m9b7whj9v2t6v.png)

*Refer GIT Repository Details :* 

[Link] https://github.com/priyankanandula/SpringBoot-REST-API-CRUD

> In next blog I will explain how to Consume these REST APIS using RestTemplate inside the code.

Have a Good Day, this is _priyanka nandula_ signing off...