Setting Up Swagger 2 with a Spring REST API

Setting Up Swagger 2 with a Spring REST API

Spring Boot – Creating Docker Image

 

 

In this tutorial, we’ll look at Swagger 2 for a Spring REST web service, using the Springfox implementation of the Swagger 2 specification. If you are not familiar with Swagger.how to

 Adding the Maven Dependency

plugins {
    id 'org.springframework.boot' version '2.7.5'
    id 'io.spring.dependency-management' version '1.0.15.RELEASE'
    id 'java'
}

group = 'com.student.management'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    runtimeOnly 'com.mysql:mysql-connector-j'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    // https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui
    implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
    implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
}

tasks.named('test') {
    useJUnitPlatform()
}


Integrating Swagger 2 Into the Project

 

package com.student.management.studentmangement;

import com.google.common.base.Predicates;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class StudentmangementApplication {

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

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .paths(Predicates.not(PathSelectors.regex("/(error|auditevents|loggers|health|env|metrics|heap|refresh|heap|archaius|autoconfig|bean|channel|config|dump|features|info|mapping|trace).*")))
                .build();
    }

}


    Student Controller class 


package com.student.management.studentmangement.API;

import com.student.management.studentmangement.Request.AddStudent;
import com.student.management.studentmangement.Request.updateRequest;
import com.student.management.studentmangement.Response.DefaultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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.RestController;

@RestController
public class StudentController {

    @Autowired
    StudentService service;

    @PostMapping("/add/student")
    public ResponseEntity addStudent(@RequestBody AddStudent request)
    {
        ResponseEntity response=null;

        try {

            response = new ResponseEntity(service.addStudent(request),HttpStatus.OK);

        }catch (Exception e){
            response=new ResponseEntity(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return response;
    }


    @PutMapping("/update/student")
    public ResponseEntity updatestudent(@RequestBody updateRequest request){

        ResponseEntity responseEntity=null;

        try {

          DefaultResponse  response = service.updateStudent(request);

          if (response.getResponseCode().equals("200")){
              responseEntity=new ResponseEntity(response,HttpStatus.OK);
          }
          else if (response.getResponseCode().equals("500")){
              responseEntity=new ResponseEntity(response,HttpStatus.INTERNAL_SERVER_ERROR);
          }

        }catch (Exception e){
         responseEntity=new ResponseEntity(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
        }
      return  responseEntity;
    }
   }

Student Service Class 


package com.student.management.studentmangement.API;

import com.student.management.studentmangement.Course.CourseRepository;
import com.student.management.studentmangement.Request.AddStudent;
import com.student.management.studentmangement.Request.updateRequest;
import com.student.management.studentmangement.Response.DefaultResponse;
import com.student.management.studentmangement.StudentIntity.Student;
import com.student.management.studentmangement.StudentIntity.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class StudentService {

    @Autowired
    StudentRepository studentRepository;
    @Autowired
    CourseRepository courseRepository;

   public DefaultResponse addStudent(AddStudent request){
       DefaultResponse defaultResponse=null;

       try {

           if (request.getStudent().getStname()==null && request.getStudent().getStname().isEmpty()){
               throw new Exception("Sudent is null or empty ");
           }
           studentRepository.save(request.getStudent());
           defaultResponse=new DefaultResponse("successfull","sutdent has been added","200",""+request.getStudent().getId());

       }catch (Exception e){

           defaultResponse=new DefaultResponse("failure ","student has been not added","500",""+request.getStudent().getId());
       }
   return defaultResponse;
   }

   public DefaultResponse updateStudent(updateRequest request){

       DefaultResponse response=null;
       Student student=null;
       try {

           if (request.getStudent()!=null){
                student=studentRepository.findStudentsById(request.getStudent().getId());

                student.setStname(request.getStudent().getStname());
                student.setFee(request.getStudent().getFee());
                student.setCourseList(request.getStudent().getCourseList());
           }

           studentRepository.save(student);
           response=new DefaultResponse("successful ","student has been update","200",""+request.getStudent().getId());

       }catch (Exception e){

           response=new DefaultResponse("failure","student has not be update","500",""+request.getStudent().getId());
       }
       return response;
   }


}

Course Entity class

package com.student.management.studentmangement.Course;

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

@Entity
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String coursename;
    private int duration;

    public Long getId() {
        return id;
    }

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

    public String getCoursename() {
        return coursename;
    }

    public void setCoursename(String coursename) {
        this.coursename = coursename;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }
}

Course Repository 

package com.student.management.studentmangement.Course;

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

public interface CourseRepository extends JpaRepository<Course,Long> {

}

Student Entity Class 

package com.student.management.studentmangement.StudentIntity;

import com.student.management.studentmangement.Course.Course;

import javax.persistence.*;
import java.util.List;

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String stname;
    private int fee;

    @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    public List<Course> courseList;


    public Long getId() {
        return id;
    }

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

    public String getStname() {
        return stname;
    }

    public void setStname(String stname) {
        this.stname = stname;
    }

    public int getFee() {
        return fee;
    }

    public void setFee(int fee) {
        this.fee = fee;
    }

    public List<Course> getCourseList() {
        return courseList;
    }

    public void setCourseList(List<Course> courseList) {
        this.courseList = courseList;
    }
}

Student Repsitory

package com.student.management.studentmangement.StudentIntity;

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

import java.util.Optional;

public interface StudentRepository extends JpaRepository<Student,Long> {


     Student findStudentsById(Long id);
}


Request Class 
student add request class is used to add data in entity through request.this is the professional method.
in i will made AddStudent class.
  

package com.student.management.studentmangement.Request;

import com.student.management.studentmangement.StudentIntity.Student;

public class AddStudent {
    Student student;

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }
}


Update student request class

package com.student.management.studentmangement.Request;

import com.student.management.studentmangement.StudentIntity.Student;

public class updateRequest {
    Student student;


    public void setStudent(Student student) {
        this.student = student;
    }

    public Student getStudent() {
        return student;
    }
}

Application properties file 

spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/student
spring.datasource.username=root
spring.datasource.password=
spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
server.port=8180
Swagger Implement URL are given below.

http://localhost:8180/swagger-ui.html




Setting Up Swagger 2 with a Spring REST API Using Springfox
http://localhost:8180/v2/api-docs Setting Up Swagger 2 with a Spring REST API Using Springfox how to Create Docker image in Spring boot Application Create Dockerfile file and past
FROM openjdk:8-jdk-alpine
ADD /build/libs/Studentmangement-0.0.1-SNAPSHOT.jar Studentmangement-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar","/Studentmangement-0.0.1-SNAPSHOT.jar"]
EXPOSE 8180


make sure you have install docker in your system


if you not install docker in your install docker follow step for kali linux or other linux os.

sudo apt install docker press enter


after install the docker now you ready to create docker image.


sudo docker build -t student-mangement-service .

sudo docker --network "host" student-mangement-service



Coagulation you have been deploy first spring boot application on docker. 



 

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *