Spring Boot Webflux: RouterFunctions Add Query Parameters - spring

I am trying to figure out how to add query parameters to a route when using RouterFunctions. Here's what I have so far:
#Bean
public RouterFunction<ServerResponse> routes() {
return
RouterFunctions.route()
.GET("/one/{one}", routeHandlerOne::handlerOne)
.GET("/two", routeHandlerOne::handlerTwo)
.build();
}
For route two I want add a query parameter, like /two?three. Any help would be most helpful, thank you!

There is a queryParam() method on the RequestPredicates class you can use.
RouterFunctions.route()
.GET("/one", RequestPredicates.queryParam("test", t -> true), new CustomHanlder())
.build();
There are two overloaded methods for queryParam(). One takes the exact value to compare against (javadoc). The second (the one in the example above) takes a predicate and will delegate to the handler function if the predicate returns true (javadoc).
You can then access the query params through the ServerRequest object in your handler function ie.
serverRequest.queryParam("test")

If you want multiple query parameters then you can do it this way
.GET("/login", RequestPredicates.all()
.and(queryParam("username", t -> true))
.and(queryParam("password", t -> true)), handler::login)

Related

Passing a param as a query string or part of url?

Should you pass a param to a GET request as part of the URL or as a query string, for example?
Route::get('/image/{id}', 'ImageController#get');
Should we do:
/image/10
/image?id=10
The question of which approach should you do is one I won't answer, as that's entirely up to you to determine which method you'd want to do.
With your current Route, only one of the supplied URLs would hit the get() method in your ImageController.
/image/10 matches your Route, and would be used as:
public function get($id){
dd($id); // 10
}
/image?id=10 doesn't match your URL, and would be a 404 due to a missing parameter. The route would need to be modified to:
Route::get('/image', 'ImageController#get');
And your Controller method would need to be:
public function get(Request $request){
$id = $request->input('id');
dd($id); // 10
}
There's pros and cons to each approach, Query String params are good for multiple required and/or option parameters, while URL params are better suited to single required/optional. Multiple optional URL params is not something that is supported, so keep that in mind.

How to just get the data using CRUD POST method?

I have developed Small Spring boot Rest api app. I can able to get the data or create new record and search with paging and sorting.
Now i'm looking for provide input data in body to get the data instead of providing in URL with GET method. Is this method also default function ? Please advise.
public interface CodeTextRepository extends PagingAndSortingRepository<CodeText, Long> {
}
How to write POST method to just get the data ?
http://localhost:8080/api/code
method : POST
{
"code":1
}
If I understand you correctly, you want to create a controller that will get the a model as body parameter ({ "code": 1 }) in a POST method and then do something with it.
To do that, you can create a controller that looks like the following (I inserted pseudo-code as an example):
#RestController
#RequestMapping(value = "/api/code")
public class CodeTextController {
private CodeTextRepository codeTextRepository;
// constructor injection
public CodeTextController(CodeTextRepository codeTextRepository) {
this.codeTextRepository = codeTextRepository;
}
#PostMapping
public CodeText postCodeText(#RequestBody CodeTextRequest codeTextRequest) {
// some code to get from the DB
return codeText;
}
}
public class CodeTextRequest {
private int code;
// getters and setters
}
Simply add Accept header to the request, like
accept: application/json
Spring Data-Rest will return the body after a POST request if either the returnBodyOnCreate flag was explicitly set to true in the RepositoryRestConfiguration OR if the flag was NOT set AND the request has an Accept header.
You can set the flag directly during configuration, or you can set it via the application.properties:
spring.data.rest.returnBodyOnCreate = true
you can also set it separately for update:
spring.data.rest.returnBodyOnUpdate = true
---- edit
Maybe I misunderstood your question. If you simply want to GET an existing data using POST method, then DO NOT DO IT AT ALL! That's not a REST API any more. There must be some reason you want to do it, but you should try do resolve that original problem instead in another way!

How to get Swagger UI to display similar Spring Boot REST endpoints?

I have a controller class with two endpoints
#RestController
#RequestMapping
public class TestController {
#RequestMapping(
value= "/test",
method = RequestMethod.GET)
#ResponseBody
public String getTest() {
return "test without params";
}
#RequestMapping(
value= "/test",
params = {"param"},
method = RequestMethod.GET)
#ResponseBody
public String getTest(#PathParam("param") int param) {
return "test with param";
}
}
One has a parameter, one doesn't, and the both work.
If I use curl or a web browser to hit the endpoints
http://localhost:8081/test
returns
test without params
and
http://localhost:8081/test?param=1
returns
test with param
but the swagger ui only shows the one without a parameter.
If I change the value in the request mapping for the request with a parameter to
#RequestMapping(
value= "/testbyparam",
params = {"param"},
method = RequestMethod.GET)
Swagger UI displays both endpoints correctly, but I'd rather not define my endpoints based on what swagger will or won't display.
Is there any way for me to get swagger ui to properly display endpoints with matching values, but different parameters?
Edit for Clarification:
The endpoints work perfectly fine; /test and /test?param=1 both work perfectly, the issue is that swagger-ui won't display them.
I would like for swagger ui to display the endpoints I have defined, but if it can't, then I'll just have to live with swagger-ui missing some of my endpoints.
Edit with reference:
The people answering here: Proper REST formatted URL with date ranges
explicitly say not to seperate the query string with a slash
They also said "There shouldn't be a slash before the query string."
The issue is in your Request Mapping, The second method declaration is overriding the first method. As Resource Mapping value is same.
Try changing the second method to below. As you want to give input in QueryParam rather than path variable, you should use #RequestParam not #PathParam.
Note that you have to give /test/, In order to tell Spring that your mapping is not ambiguous. Hope it helps.
#RequestMapping(
value= "/test/",
method = RequestMethod.GET)
#ResponseBody
public String getTest (#RequestParam("param") int param) {
return "test with param"+param;
}
Upon reading clarifications, the issue here is that swagger-ui is doing the correct thing.
You have two controller endpoints, but they are for the same RESOURCE /test that takes a set of optional query parameters.
Effectively, all mapped controller endpoints that have the same method (GET) and request mapping (/test) represent a single logical resource. GET operation on the test resource, and a set of optional parameters which may affect the results of invoking that operation.
The fact that you've implemented this as two separate controller endpoints is an implementation detail and does not change the fact that there is a single /test resource that can be operated upon.
What would be the benefit to consumers of your API by listing this as two separate endpoints in swagger UI vs a single endpoint with optional parameters? Perhaps it could constrain the set of allowed valid query parameters (if you set ?foo you MUST set &bar) but this can also be done in descriptive text, and is a much more standard approach. Personally, I am unfamiliar with any publicly documented api that distinguishes multiple operations for the same resource differentiated by query params.
As per Open API Specification 3
OpenAPI defines a unique operation as a combination of a path and an
HTTP method. This means that two GET or two POST methods for the same
path are not allowed – even if they have different parameters
(parameters have no effect on uniqueness).
Reference - https://swagger.io/docs/specification/paths-and-operations/
This was also raised as an issue but it was closed because OAS3 doesn't allow that -
https://github.com/springdoc/springdoc-openapi/issues/859
Try including the param in the path as below.
#GetMapping("/test/{param}")
public String getTest(#PathVariable final int param) {
return "test with param";
}
I'm unclear exactly what you're attempting to do, but I'll give two solutions:
If you want to have PATH parameters e.g. GET /test & GET /test/123 you can do:
#GetMapping("/test")
public String getTest() {
return "test without params";
}
#GetMapping("test/{param}")
public String getTest(#PathVariable("param") int param) {
return "test with param";
}
If you want query parameters (GET /test and GET /test?param=123) then you need a single endpoint that takes an optional parameter:
#GetMapping("test")
public String getTest(#RequestParam("param") Integer param) {
if(param == null) {
return "test without params";
} else {
return "test with param";
}
}

Spring 5 Reactive Handler Function

I want to specify a query param in Router Function with Spring 5 web reactive. Here my example:
/api/cars?model={model}
but when I replace the query param by a value, it is route to the url :
/api/cars
and not the one with the query param.
In fact, I have found the solution few months ago. I post the code maybe it will helps. Here my example
#Bean
public RouterFunction<ServerResponse> routerFunction() {
return route(GET("/cars"), carHandler::handleFindAll)
.and(route(GET("/cars?model={model}"), carHandler::handleFindAll));
// no need tho specify the request param into the route
}
Here my handler
public Mono<ServerResponse> handleFindAll(ServerRequest request) {
request.queryParam("model"); // will contains the request param ?cars/model=Audi
return ServerResponse.ok().body(initCars(), Car.class);
}
and how we manage find all and find all with request param

Is it possible to return value from Spring AspectJ?

I'm returning value from my controller. Let it be ResponseEntity<String> type.
Controller returns:
new ResponseEntity<String>("{\"msg\":\"success\"}",HttpStatus.OK);
Following value goes to my spring aspect. I am receiving this object in following code:
#AfterReturning(pointcut = "somePointcut()",returning = "retVal")
public ResponseEntity<String> adviceTest3(Object retVal) {
//here i have access to controller's object
return new ResponseEntity<String>("{\"msg\":\"changed value within aspect\"}",HttpStatus.OK);
}
I'm aware that there is #AfterReturning. Is it any way manipulate data and achieve that?
With #AfterReturning, no. Quote from the documentation
An after returning advice has access to the return value (which it cannot modify), invoked method, methods arguments and target.
You could use #Around instead.

Resources