"Welcome To Ashok IT" "Spring Boot & Microservices" Topic : Rest API Development Date : 12/06/2025 (Session - 65) _____________________________________________________________________________________________________________________________ Mini Project Setup ================== * We Will be Implementing the Rest API Development with Mini Project(GET,POST,PUT,PATCH,DELETE) * As part of this mini project development will be covering with below concepts 1) Rest API Development with Database Interaction 2) Swagger Documentation Configuration for Rest API Mini Project 3) Exception Handling in Rest API Development 1) Creating the Spring boot Starter Project using below starter * Web Starter * Oracle Driver * Lombok * ModelMapper(Collect From Maven Repoistory) * Spring Boot Dev Tools 2) Creating the Following packages to organize our classes in project com.ashokit |-> Application.java com.ashokit.constants |-> ApplicationConstants.java com.ashokit.controller |-> PersonController.java com.ashokit.dao |-> PersonDao.java com.ashokit.service |-> PersonService.java |-> PersonServiceImpl.java com.ashokit.dto |-> PersonDTO.java com.ashokit.entity |-> Person.java com.ashokit.exception |-> ResourceNotFoundException.java com.ashokit.response |-> PageResponse.java pom.xml ======= 4.0.0 org.springframework.boot spring-boot-starter-parent 3.4.5 com.ashokit 36_SpringBootRest_MiniProject_App 0.0.1-SNAPSHOT war 36_SpringBootRest_MiniProject_App SpringBoot Rest API Mini Project 17 org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-devtools runtime true com.oracle.database.jdbc ojdbc8 runtime org.projectlombok lombok true org.springframework.boot spring-boot-starter-tomcat provided org.springframework.boot spring-boot-starter-test test org.modelmapper modelmapper 3.1.1 com.fasterxml.jackson.dataformat jackson-dataformat-xml org.springdoc springdoc-openapi-starter-webmvc-ui 2.2.0 org.springframework.boot spring-boot-maven-plugin application.properties ====================== #server port changing server.port=8899 #Database Configuration spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe spring.datasource.username=system spring.datasource.password=manager #Hibernate Configuration spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true #FileUploading Configurations project.images=profilepics spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB Person.java =========== package com.ashokit.entity; import java.time.LocalDate; import java.time.LocalDateTime; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Entity @Table(name="ashokit_persons") @NoArgsConstructor @AllArgsConstructor @Getter @Setter @ToString public class Person { @Id @Column(name="person_id",nullable = false) @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name="person_name") private String name; @Column(name="location") private String location; @Column(name="email_id") private String emailId; @Column(name="address") private String address; @Column(name="created_dt") @Temporal(TemporalType.TIMESTAMP) private LocalDateTime createdDate; } PersonDTO.java ============== package com.ashokit.dto; import java.time.LocalDateTime; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @Builder @Schema(description = "Request Payload for Creating the Person Record....") public class PersonDTO { @Schema(description = "PersonID Will be auto generated....") private Integer id; @Schema(description = "PersonName",example = "Mahesh") private String name; @Schema(description = "PersonLocation",example="Hyderabad") private String location; @Schema(description = "PersonEmailID",example="mahesh.ashokit@gmail.com") private String emailId; @Schema(description = "PersonAddress",example="Hyderabad,Ameerpet") private String address; @Schema(description = "Person Record CreatedData Will be autogenerated.....") private LocalDateTime createdDate; } PersonService.java ================== package com.ashokit.service; import java.util.List; import org.springframework.web.multipart.MultipartFile; import com.ashokit.dto.PersonDTO; import com.ashokit.response.PageResponse; public interface PersonService { //Getting all Persons with out pagination public List getAllPersons(); //Getting all Persons with pagination public PageResponse getAllPersons(Integer pageNumber,Integer pageSize,String sortBy,String sortDirection); } PersonServiceImpl.java ====================== package com.ashokit.service; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.ashokit.dao.PersonDao; import com.ashokit.dto.PersonDTO; import com.ashokit.entity.Person; import com.ashokit.exceptions.ResourceNotFoundException; import com.ashokit.response.PageResponse; @Service public class PersonServiceImpl implements PersonService { @Autowired private PersonDao personDao; @Autowired private ModelMapper modelMapper; @Override public List getAllPersons() { List allPersons = personDao.findAll(); //converting from List into List //allPersons.stream() -> converting List into Stream object //map() -> Its is a intermediate stream operation which take one input(Person) and give it as one output(PersonDTO) //collect() -> It is a terminal operation to collect data into single object //Collectors -> It is utility class from Java8 Stream library to collect data into list,set,map object // i.e..,Collectors.toList(), Collectors.toSet(), Collectors.toMap() List allPersonDtos = allPersons.stream().map(eachPerson ->{ return new PersonDTO(eachPerson.getId(),eachPerson.getName(), eachPerson.getLocation(),eachPerson.getEmailId(), eachPerson.getAddress(),eachPerson.getCreatedDate()); }).collect(Collectors.toList()); return allPersonDtos; } @Override public PageResponse getAllPersons(Integer pageNumber, Integer pageSize, String sortBy, String sortDirection) { //sortBy ::: Sorting Field Sort sort = Sort.by(sortBy).descending(); if("asc".equalsIgnoreCase(sortDirection)) { sort = sort.by(sortBy).ascending(); } //Creating the PageRequest Object Pageable pageable = PageRequest.of(pageNumber, pageSize, sort); //Get All the Records based on Pagination Page pageInfo = personDao.findAll(pageable); //Getting the pagecontent from above Page object List personList = pageInfo.getContent(); //Converting List into List //modelMapper -> predefined class from modelMapper library. // -> We represented this class as spring bean then we can autowire anywhere in our application // -> Modelmapper contains map() which takes two arguments first argument-> source type // -> Second argument -> destination type // -> return type -> destination type List personDTOList = personList.stream() .map(eachPerson -> this.modelMapper.map(eachPerson, PersonDTO.class)) .collect(Collectors.toList()); //Creating PageResponse Object for setting pagination Information PageResponse pageResponse = new PageResponse(); pageResponse.setContent(personDTOList); pageResponse.setPageNumber(pageInfo.getNumber()); pageResponse.setPageSize(pageInfo.getSize()); pageResponse.setTotalElements(pageInfo.getTotalElements()); pageResponse.setTotalPages(pageInfo.getTotalPages()); pageResponse.setLastPage(pageInfo.isLast()); return pageResponse; } } PageResponse.java ================== package com.ashokit.response; import java.util.List; import com.ashokit.dto.PersonDTO; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @AllArgsConstructor @Setter @Getter public class PageResponse { //Holding page specific records private List content; private int pageNumber; private int pageSize; private long totalElements; private long totalPages; //If current page is lastPage means will return true otherwise will return false private boolean lastPage; } Application.java ================ package com.ashokit; import org.modelmapper.ModelMapper; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } //Making ModelMapper as SpringBean @Bean public ModelMapper getModelMapper() { return new ModelMapper(); } } PersonController.java ===================== public class PersonController { @Autowired private PersonService personService; @GetMapping(value="/",produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity getAllPersonsInformation( @RequestParam(name="pageNumber",defaultValue=ApplicationConstants.PAGE_NUMBER, required=false) Integer pageNumber, @RequestParam(name="pageSize",defaultValue=ApplicationConstants.PAGE_SIZE, required=false) Integer pageSize, @RequestParam(name="sortBy",defaultValue=ApplicationConstants.SORT_BY, required=false) String sortBy, @RequestParam(name="sortDir",defaultValue=ApplicationConstants.SORT_DIR, required=false) String sortDirection){ //Calling service method to get records with pagination PageResponse paginationData = personService.getAllPersons(pageNumber,pageSize,sortBy,sortDirection); return new ResponseEntity(paginationData,HttpStatus.OK); } } POST Request API ================ package com.ashokit.service; import java.util.List; import org.springframework.web.multipart.MultipartFile; import com.ashokit.dto.PersonDTO; import com.ashokit.response.PageResponse; public interface PersonService { //creating the new Person public PersonDTO createNewPerson(PersonDTO personDTO) throws Exception; //Getting all Persons with out pagination public List getAllPersons(); //Getting all Persons with pagination public PageResponse getAllPersons(Integer pageNumber,Integer pageSize,String sortBy,String sortDirection); } PersonServiceImpl.java ====================== package com.ashokit.service; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDate; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.ashokit.dao.PersonDao; import com.ashokit.dto.PersonDTO; import com.ashokit.entity.Person; import com.ashokit.exceptions.ResourceNotFoundException; import com.ashokit.response.PageResponse; @Service public class PersonServiceImpl implements PersonService { @Autowired private PersonDao personDao; @Autowired private ModelMapper modelMapper; @Override public PersonDTO createNewPerson(PersonDTO personDTO) throws Exception { //Input Received as DTO and we need to Convert into Entity Class i.e.,Person Person personObj = this.modelMapper.map(personDTO, Person.class); //Setting Current Data While inserting the record personObj.setCreatedDate(LocalDate.now()); //save the personObj into Database Person savedPersonObj = personDao.save(personObj); //Converting Back from Entity Class Object into DTO Class Object PersonDTO savedPersonDetails = this.modelMapper.map(savedPersonObj, PersonDTO.class); return savedPersonDetails; } @Override public List getAllPersons() { List allPersons = personDao.findAll(); //converting from List into List //allPersons.stream() -> converting List into Stream object //map() -> Its is a intermediate stream operation which take one input(Person) and give it as one output(PersonDTO) //collect() -> It is a terminal operation to collect data into single object //Collectors -> It is utility class from Java8 Stream library to collect data into list,set,map object // i.e..,Collectors.toList(), Collectors.toSet(), Collectors.toMap() List allPersonDtos = allPersons.stream().map(eachPerson ->{ return new PersonDTO(eachPerson.getId(),eachPerson.getName(), eachPerson.getLocation(),eachPerson.getEmailId(), eachPerson.getAddress(),eachPerson.getCreatedDate()); }).collect(Collectors.toList()); return allPersonDtos; } @Override public PageResponse getAllPersons(Integer pageNumber, Integer pageSize, String sortBy, String sortDirection) { //sortBy ::: Sorting Field Sort sort = Sort.by(sortBy).descending(); if("asc".equalsIgnoreCase(sortDirection)) { sort = sort.by(sortBy).ascending(); } //Creating the PageRequest Object Pageable pageable = PageRequest.of(pageNumber, pageSize, sort); //Get All the Records based on Pagination Page pageInfo = personDao.findAll(pageable); //Getting the pagecontent from above Page object List personList = pageInfo.getContent(); //Converting List into List //modelMapper -> predefined class from modelMapper library. // -> We represented this class as spring bean then we can autowire anywhere in our application // -> Modelmapper contains map() which takes two arguments first argument-> source type // -> Second argument -> destination type // -> return type -> destination type List personDTOList = personList.stream() .map(eachPerson -> this.modelMapper.map(eachPerson, PersonDTO.class)) .collect(Collectors.toList()); //Creating PageResponse Object for setting pagination Information PageResponse pageResponse = new PageResponse(); pageResponse.setContent(personDTOList); pageResponse.setPageNumber(pageInfo.getNumber()); pageResponse.setPageSize(pageInfo.getSize()); pageResponse.setTotalElements(pageInfo.getTotalElements()); pageResponse.setTotalPages(pageInfo.getTotalPages()); pageResponse.setLastPage(pageInfo.isLast()); return pageResponse; } } PersonController.java ===================== package com.ashokit.controller; import java.time.LocalDateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.ashokit.constants.ApplicationConstants; import com.ashokit.dto.PersonDTO; import com.ashokit.exceptions.ErrorDetails; import com.ashokit.exceptions.ResourceNotFoundException; import com.ashokit.response.PageResponse; import com.ashokit.service.PersonService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; @RestController @RequestMapping("/api/persons") @Tag(name="Person",description = "Person Controller Rest API Methods") public class PersonController { @Autowired private PersonService personService; @PostMapping(value="/",consumes = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity createNewPerson(@RequestBody PersonDTO personDTO) throws Exception{ PersonDTO savedPersonDTO = personService.createNewPerson(personDTO); return new ResponseEntity(savedPersonDTO,HttpStatus.CREATED); } } +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++