I’m developing an API for college courses and I want the requests to be able to handle multiple query parameters that refine the search in different ways. Example with 2 parameters:
http://url.com/api/courses/search?subject=CSCI&number=1302
I’m trying to figure out a way I can handle all the different parameters for the search header in one method in the service class. I want the parameters to be able to be in any order, and with any number of parameters (a request may have 0 or as many as the API supports). Right now, the code is only set up to support one parameter at a time. The subject header accepts any parameters and the List gets unpacked in the CourseService.java. I assume there’s an easier way to do this than writing a new if case for each combination of parameters?
Perhaps something like this pseudocode, with each one further refining the past result:
search(fullDatabase, param1);
search(search1, param2);
search(search2, param3);
Here’s my current code:
CourseController.java
@RestController
@RequestMapping("/api/courses")
public class CourseController {
@Autowired
private CourseService courseService;
@RequestMapping("/search")
public List<Course> searchCourses(@RequestParam Map<String, String> params) {
return courseService.getCourses(params);
}
}
CourseService.java
@Service
public class CourseService {
@Autowired
private CourseRepository courseRepository;
/** Handles all logic for query parameters. */
public List<Course> getCourses(Map<String, String> params) {
if (params.keySet().contains("crn")) {
return courseRepository.findByCrn(params.get("crn"));
} else if (params.keySet().contains("subject")) {
return courseRepository.findBySubject(params.get("subject"));
} else if (params.keySet().contains("number")) {
return courseRepository.findByNumber(params.get("number"));
} else if (params.keySet().contains("seats")) {
return courseRepository.findBySeats(params.get("seats"));
}
throw new QueryArgumentException(null, getClass(), params);
}
}
CourseRepository.java
@Repository
public interface CourseRepository extends JpaRepository<Course, Integer> {
@Query("FROM Course WHERE crn = ?1")
List<Course> findByCrn(String crn);
@Query("FROM Course WHERE subject = ?1")
List<Course> findBySubject(String subject);
@Query("FROM Course WHERE number = ?1")
List<Course> findByNumber(String number);
@Query("FROM Course WHERE department = ?1")
List<Course> findByDepartment(String department);
@Query("FROM Course WHERE seats >= ?1")
List<Course> findBySeats(String seats);
}
1