Creating RESTful web service in SpringBoot [Spring Basics-6 ]

REST api

  • REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol.

  • A RESTful web service usually defines a URI, Uniform Resource Identifier a service, provides resource representation such as JSON and set of HTTP Methods.

  • @GetMapping,@PostMapping,@PutMapping,DeleteMapping or @RequestMapping(path="courses",RequestMethod.Get) : HTTP methods

  • @PathVariable: We can use it to dynamically get content from URI. ex -

    @GetMapping("/courses/{courseId}") 
    public Course getCourse(@PathVariable String courseId){
     // Do stuff with courseId
    }
    
  • @RequestBody: When doing post methods, in order to use JSON data in body, we make use of RequestBody. ex -
    @PostMapping(path="/courses",consumes="application/json")
      public Course addCourse(@RequestBody Course c) {
          // Do stuff with c
      }
    

REST api example -

REST endpoints:

  • GET /students (Get all students)
  • GET /students/{studentsId} (Get specific student)
  • POST /students (Add a student)
  • PUT /students (Edit a student)
  • DELETE /students/{studentId} (Delete specific student)

Student.java

@Entity
public class Course {
    @Id
    private Long id;
    private String name;
    //Getters,Setters & constructors

StudentDao.java

public interface StudentDao extends JpaRepository<Student,Long>{}

StudentService.java : interface

public interface CourseService {
    public List<Student> getAllStudents();
    public Optional<Student> getStudent(long id);
    public Student addStudent(Student s);
    public Student updateStudent(Student s);
    public void deleteStudent(long id);
}

StudentServiceImpl.java

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao studentdao;

    public StudentServiceImpl() {}

    @Override
    public List<Student> getAllStudents() {    return studentdao.findAll();    }

    @Override
    public Optional<Student> getStudent(long id) {    return studentdao.findById(id);        }

    @Override
    public Student addStudent(Student s) {    return studentdao.save(s);    }

    @Override
    public Student updateStudent(Student s) {    return studentdao.save(s);    }

    @Override
    public void deleteStudent(long id) {    studentdao.deleteById(id);    }
}

StudentController.java

@RestController
public class StudentController {
    @Autowired
    private StudentService studentservice;

    @GetMapping("/students")
    public List<Course> getAllStudents(){    return this.studentservice.getAllStudents();    }

    @GetMapping("/students/{studentId}")
    public Optional<Course> getStudent(@PathVariable String studentId){ 
        //@PathVariable is used to dynamically get courseId given in URL
        return this.studentservice.getStudent(Long.parseLong(studentId));
    }

    @PostMapping(path="/students",consumes="application/json")
    public Course addStudent(@RequestBody Student s) {    return this.studentservice.addStudent(s);    }

    @PutMapping("/students")
    public Course updateStudent(@RequestBody Student c) {    return this.studentservice.updateStudent(s);    }

    // In this particular function, it is shown how to send HTTP status codes back
    @DeleteMapping("/students/{studentId}")
    public ResponseEntity<HttpStatus> deleteStudent(@PathVariable String studentId) {
        try {
            this.studentservice.deleteStudent(Long.parseLong(studentId));
            return new ResponseEntity<>(HttpStatus.OK);
        } catch(Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }    
}

application.properties

# can change server port
server.port=8080

# database configs - mysql
spring.datasource.url=jdbc:mysql://localhost:3306/springrest
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# hibernate cofigs
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect

Code link
References - Learn Code with Durgesh
Article by - Arjit Sharma

Did you find this article valuable?

Support Arjit Sharma by becoming a sponsor. Any amount is appreciated!