The project I’m working on has a REST API endpoint /api/v1/exportreport. It’s simple enough - it allows users to specify a date range and will produce a response containing data within the specified range that is then exported to a CSV file.
I’m a little confused by how the parameterisation of the endpoint has been written. By viewing the call made by the front-end code in the console of the browser I’m using, I can see that it’s calling the endpoint with these parameters
That’s all fine. However here is the Java code in the controller that handles this request
That “parameters” map is what’s confusing me. The code is working (I’ve tested it via the front-end) but I don’t know how or where the “fromDate” and “toDate” parameters are being slotted into a Map. Is this something that Spring Boot does behind the scenes? Furthermore, do you think this is good design? I’ve not shown the code that validates the parameters contained in the Map (basically, there is a configurable list of required parameters for this endpoint, which the service checks to see if they’re present in the Map) but the contents of the Map are used to build a query that is executed using a JdbcTemplate.
It's a bit of a lazy way of dealing with two parameters.
But yes, Spring extracts the parameters into a Map, which is what is passed in via that annotation.
Though I would have expected Map<String,String>, since that 's what it is.
I expect there's some unnecessary casting done later on when the value Object is parsed to a Date.
You can use @RequestParam this way, or you can use them for each query / form parameter separately. For instance, @RequestParam("fromDate") String fromDate, @RequestParam("toDate") String toDate. You may even be able to change the type now, and have Spring convert the strings for you.
Rob Spoor wrote:You can use @RequestParam this way, or you can use them for each query / form parameter separately. For instance, @RequestParam("fromDate") String fromDate, @RequestParam("toDate") String toDate. You may even be able to change the type now, and have Spring convert the strings for you.
Yeah, I've always used @RequestParam for each parameter separately, which is why I was confused by the use of the Map.
Simon Ritchie wrote:That's a Swagger annotation. I forgot to remove it before posting the code.
Just out of curiosity, what artifact and version of swagger is that ? Because in newest version there's no such annotation in swagger-annotation artifact, there's @ApiParam which seems similar, maybe replacement.
eat bricks! HA! And here's another one! And a tiny ad!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop