Let’s say you want to create a Spring Boot REST API which accepts URL and query parameters.
How do you retrieve those parameters in the code ?
By using
@RequestParam annotation for query parameter
@PathVariable annotation for URL parameter
Here is an example:
@GetMapping("/restService/{urlParameter}")
public Map<String,String> restService(@PathVariable("urlParameter") String urlParameter,@RequestParam("queryParameter") String queryParameter){
Map<String,String> response = new HashMap<>();
response.put("urlParameter", urlParameter);
response.put("queryParameter",queryParameter);
return response;
}
The above method is a GET REST service which takes in a url parameter after the relative path “restService” and also takes in a query parameter with the key “queryParameter”
The URL parameter is enclosed in braces in the relative path passed to @GetMapping annotation.
The URL parameter is then retrieved using @PathVariable annotation which takes the variable indicated in enclosed braces as a parameter.
The query parameter is not mentioned in the relative path passed to @GetMapping annotation.
Here is a sample GET request:
http://localhost:8080/restService/myURLParameter?queryParameter=myQueryParameter
myURLParameter is the URL parameter
myQueryParameter is the query parameter for the key queryParameter.
The service just returns both the parameters as a JSON.
Here is the output:

That’s it!
Leave a Reply