Mehandi Hassan
Mehandi Hassan

Reputation: 2611

How do I retrieve query parameters in a Spring Boot controller?

I am developing a project using Spring Boot. I've a controller which accepts GET requests.

Currently I'm accepting requests to the following kind of URLs:

http://localhost:8888/user/data/002

but I want to accept requests using query parameters:

http://localhost:8888/user?data=002

Here's the code of my controller:

@RequestMapping(value="/data/{itemid}", method = RequestMethod.GET)
public @ResponseBody
item getitem(@PathVariable("itemid") String itemid) {   
    item i = itemDao.findOne(itemid);              
    String itemname = i.getItemname();
    String price = i.getPrice();
    return i;
}

Upvotes: 229

Views: 538462

Answers (7)

Devang Jadav
Devang Jadav

Reputation: 1

When using the @GetMapping annotation, you typically use @RequestParam in the request instead of @RequestBody. If you want to use @RequestBody, you should use the @PostMapping annotation in the API method.

Upvotes: 0

satish gupta
satish gupta

Reputation: 91

To accept both Path Variable and query Param in the same endpoint:

@RequestMapping(value = "/hello/{name}", method = RequestMethod.POST)
    public String sayHi(
            @PathVariable("name") String name, 
            @RequestBody Topic topic,
            //@RequestParam(required = false, name = "s") String s, 
            @RequestParam Map<String, String> req) {
        
        return "Hi "+name +" Topic : "+ topic+" RequestParams : "+req;
    }

URL looks like : http://localhost:8080/hello/testUser?city=Pune&Pin=411058&state=Maha

Upvotes: 9

daparic
daparic

Reputation: 4474

To accept both @PathVariable and @RequestParam in the same /user endpoint:

@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
                 @RequestParam(required=false) Map<String,String> qparams) {
    qparams.forEach((a,b) -> {
        System.out.println(String.format("%s -> %s",a,b));
    }
  
    if (data != null) {
        System.out.println(data);
    }
}

Testing with curl:

  • curl 'http://localhost:8080/user/books'
  • curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'

Upvotes: 21

Shashank
Shashank

Reputation: 757

In Spring boot: 2.1.6, you can use like below:

    @GetMapping("/orders")
    @ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
    public List<OrderResponse> getOrders(
            @RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
            @RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
            @RequestParam(value = "location_id", required = true) String location_id) {

        // TODO...

        return response;

@ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.

Upvotes: 5

afraisse
afraisse

Reputation: 3562

Use @RequestParam

@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){

    Item i = itemDao.findOne(itemid);              
    String itemName = i.getItemName();
    String price = i.getPrice();
    return i;
}

Upvotes: 314

Andrew Grothe
Andrew Grothe

Reputation: 2374

While the accepted answer by afraisse is absolutely correct in terms of using @RequestParam, I would further suggest to use an Optional<> as you cannot always ensure the right parameter is used. Also, if you need an Integer or Long just use that data type to avoid casting types later on in the DAO.

@RequestMapping(value="/data", method = RequestMethod.GET)
public @ResponseBody
Item getItem(@RequestParam("itemid") Optional<Integer> itemid) { 
    if( itemid.isPresent()){
         Item i = itemDao.findOne(itemid.get());              
         return i;
     } else ....
}

Upvotes: 34

TKPhillyBurb
TKPhillyBurb

Reputation: 171

I was interested in this as well and came across some examples on the Spring Boot site.

   // get with query string parameters e.g. /system/resource?id="rtze1cd2"&person="sam smith" 
// so below the first query parameter id is the variable and name is the variable
// id is shown below as a RequestParam
    @GetMapping("/system/resource")
    // this is for swagger docs
    @ApiOperation(value = "Get the resource identified by id and person")
    ResponseEntity<?> getSomeResourceWithParameters(@RequestParam String id, @RequestParam("person") String name) {

        InterestingResource resource = getMyInterestingResourc(id, name);
        logger.info("Request to get an id of "+id+" with a name of person: "+name);

        return new ResponseEntity<Object>(resource, HttpStatus.OK);
    }

See here also

Upvotes: 4

Related Questions