Exposing RESTful APIs in Spring
In this post I will demonstrate how we can expose RESTful services with Spring. Our goal will be extending our source code from previous tutorial and separating the Search functionality to search a course with either name or code.
Exposing data as JSON can be achieved in 2 ways.
Option 1: Binding value to a controller method return
As of now we have only seen to return view page names with path as string value from our controller methods. That is how MVC works. But in our current example we will return data instead of view page. To do this, we need to add @ResponseBody annotation before our controller method. Also the return type will be according to our need.
@GetMapping(value = "/course/search")
public @ResponseBody
ResponseEntity<?> searchCourseByCourseCode(@RequestParam(name = "query") String query) {
var data = courseService.searchCourse(query);
return new ResponseEntity<>(data, HttpStatus.OK);
}
Option 2: Using @RestController annotation instead of controller
If we want all methods of a class to expose data as JSON, then we can use @RestController annotation.
@RestController
@RequestMapping("/api/v1")
public class CourseRestController {
private final CourseService courseService;
public CourseRestController(CourseService courseService) {
this.courseService = courseService;
}
@GetMapping(value = "/course/search")
public ResponseEntity<?> searchCourseByCourseCode(@RequestParam(name = "query") String query) {
var data = courseService.searchCourse(query);
return new ResponseEntity<>(data, HttpStatus.OK);
}
}
Service code
The following code will be in our CourseService class.
public List<CourseDto> searchCourse(String query) {
var courses = this.courseRepository.getCoursesByQueryString(query);
var courseDtos = new ArrayList<CourseDto>();
for (var course : courses) {
var courseDto = new CourseDto();
BeanUtils.copyProperties(course, courseDto);
courseDtos.add(courseDto);
}
return courseDtos;
}
Repository Code
The following will be in our CourseRepository interface.
@Query(value = "select *" +
" from tbl_course c" +
" where c.course_name like %:keyword% " +
"or c.course_code like %:keyword%", nativeQuery = true)
List<Course> getCoursesByQueryString(@Param("keyword") String query);
The code will be found here.