Us01
Us01

Reputation: 3

How to filter multiple data within a single API path?

I have following controller

MyController.java

 @GetMapping("/checklessthan")
    public Page<User> demo(@Param(value = "age") String age,
                                                @Param(value ="page") int page,
                                                @Param(value = "size") int size){

        Pageable requestedPage = PageRequest.of(page, size);
        Page<User> user= userRepository.findAllByageLessThan(age, requestedPage);
        return user;
    }

@GetMapping("/checkgreaterthan")
    public Page<User> demo(@Param(value = "age") String age,
                                                @Param(value ="page") int page,
                                                @Param(value = "size") int size){

        Pageable requestedPage = PageRequest.of(page, size);
        Page<User> user= userRepository.findAllByageGreaterThan(age,requestedPage);
        return user;
    }

@GetMapping("/checkEquals")
    public Page<User> demo(@Param(value = "age") String age,
                                                @Param(value ="page") int page,
                                                @Param(value = "size") int size){

        Pageable requestedPage = PageRequest.of(page, size);
        Page<User> user= userRepository.findAllByageEquals(age, requestedPage);
        return user;
    }

above 3 APIs is to display the age according to it's method like lessThan, greaterThan or equals age. I want to combine all endpoints into single one.

when i only want to filter lessThanAge then result must give me output of only lessThanAge. same way if i want equalsAge than result must return only equalsAge in output.

so How can I combine above 3 APIs into single API?

Upvotes: 0

Views: 363

Answers (1)

iamatsundere181
iamatsundere181

Reputation: 1409

I do not know the whole context about your base database, but I recommend an API like these.

First option:

/get_users/age=x&operator=y&page=1&size=10

where:

  • age is the value you request
  • operator is EQUAL,GREATER or LOWER
  • sample: /get_users/age=1&operator=GREATER&page=1&size=10 means you call checkgreaterthan the age of 1

Second option:

/get_users/from_age=x&to_age=y&page=1&size=10

where:

  • from_age is the min value of age
  • to_age is the max value of age
  • sample /get_users/from_age=0&to_age=10&page=1&size=10 means you call the checklessthan with value of 10, or for overview, you'll always call by age-range

And if you can, can you please update the functions from your DBAL userRepository

Upvotes: 1

Related Questions