Restful API using Spring Boot


Restful API using Spring Boot




Nowadays Rest API is very popular concept which used when building web applications. In Rest API we can do PUT, POST, GET, DELETE requests to perform CRUD operations. Spring boot provides ability to do the implementation for Rest API. In Spring Boot we are using Maven as build tool and it is useful when installing plugins and libraries maven uses maven repository to install them. 

  1. Initialize Spring Boot Project.
  2. Database configurations.
  3. Create Database tables in MySql.
  4. Create an Entity Class.
  5. Create Data Repository and Rest Controllers.
  6. Build and run the Project.

Create the Spring Boot Project

It is very easy to initialize a spring boot using start.spring.io. we only have to do is provide project details like group id, artifact id, description, version and more importantly dependencies which we are going to use in runtime or for implementation. For this we are using mysql so we are adding MySql, JPA and Web as dependencies. After providing details we have to download the zip and import it to eclipse or what ever IDE using.

Database configurations

Add the database configuration files to src -> main -> resources -> application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/users_database?useSSL=false
spring.datasource.username = root
spring.datasource.password = root

# Hibernate ddl auto to database creation type
spring.jpa.hibernate.ddl-auto = none

Create Database tables in MySql

If database is not automatically generated by hibernate we should create tables for our spring boot project. According to our following configurations we defined not to create database sowe should create database first using mysql. (spring.jpa.hibernate.ddl-auto = none)

Create an Entity Class

Create entity class by adding appropriate annotations.

import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Seller {
    private Long id;
    private String fname;
    private String sname;
    private String phoneNumber;
    private String address;
    private String email;
    private Date joinedDate;
    
    public Seller() {
    super();
    }
    
public Seller(Long id, String fname, String sname, String phoneNumber, String address, String email,
Date joinedDate) {
super();
this.id = id;
this.fname = fname;
this.sname = sname;
this.phoneNumber = phoneNumber;
this.address = address;
this.email = email;
this.joinedDate = joinedDate;
}

public Seller(String fname, String sname, String phoneNumber, String address, String email,
Date joinedDate) {
super();
this.fname = fname;
this.sname = sname;
this.phoneNumber = phoneNumber;
this.address = address;
this.email = email;
this.joinedDate = joinedDate;
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}

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

public String getFname() {
return fname;
}

public void setFname(String fname) {
this.fname = fname;
}

public String getSname() {
return sname;
}

public void setSname(String sname) {
this.sname = sname;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getEmail() {
return email;
}

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

public Date getJoinedDate() {
return joinedDate;
}

public void setJoinedDate(Date joinedDate) {
this.joinedDate = joinedDate;
}

}

Create Data Repository, Data Service and Rest Controllers

As next step create the Repository interface and create instance in Service class.


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

public interface SellerRepository extends JpaRepository<Seller, Long>{

}

SellerSeervice.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SellerService {

@Autowired
private SellerRepository sellerRepository;
public List<Seller> listAll() {
return sellerRepository.findAll();
}
public void save(Seller seller) {
sellerRepository.save(seller);
}
public Seller get(Long id) {
return sellerRepository.findById(id).get();
}
public void delete(Long id) {
sellerRepository.deleteById(id);
}
}

after that create the Rest Controller Class

SellerController.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RestController
public class AppController {
@Autowired
private SellerService sellerService;
@RequestMapping(method = RequestMethod.GET, value="/sellers")
public List<Seller> getSellers() {
List<Seller> listSellers = sellerService.listAll();
return listSellers;
}
@RequestMapping(method = RequestMethod.POST, value="/sellers")
public Seller addSellers(@RequestBody Seller seller) {
sellerService.save(seller);
return seller;
}
@RequestMapping(method = RequestMethod.PUT, value="/sellers/{id}")
public Seller updateSeller(@PathVariable(name = "id") Long id, @RequestBody Seller seller) {
Seller getSeller = sellerService.get(id);
if(getSeller != null) {
getSeller.setFname(seller.getFname());
getSeller.setSname(seller.getSname());
getSeller.setEmail(seller.getEmail());
getSeller.setPhoneNumber(seller.getPhoneNumber());
getSeller.setAddress(seller.getAddress());
getSeller.setJoinedDate(seller.getJoinedDate());
}
sellerService.save(getSeller);
return getSeller;
}
@RequestMapping(method = RequestMethod.DELETE, value="/sellers/{id}")
public Seller deleteSeller(@PathVariable(name = "id") Long id) {
Seller getSeller = sellerService.get(id);
sellerService.delete(id);
return getSeller;
}
}

Build and run the Project

Finally right click on the project and run it as Spring Boot App. It will run on localhost. We can test GET and DELETE methods on Browser and to test PUT and POST we should use a software like Postman. It will handle the all requests.

Thank you to read till the end.








































Comments

  1. Great Info!!! Thanks for sharing information with us. If someone wants to know about Safety Softwares and Employee Management Software I think this is the right place for you.

    ReplyDelete

Post a Comment

Please make comments related to field

Popular posts from this blog

RESTful APIs using NodeJS, ExpressJS, and MS SQL Server

Full Stack Web Development

Start React-Native from Development Environment Setting Up