0

In Spring Cloud API Gateway (MVC), I am trying to filer a GET request that dynamically creates a request param (query string)?

Original request path to API Gateway with path param:

v1/sample-resource/methodName?id=id12345

I would like the filtered request path result to be:

v1/sample-resource/methodName/id12345

Is there any documentation available that shows how to do this? I've seen:

RewritePath Filter

https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-mvc/filters/rewritepath.html

AddRequestParameter Filter

https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-mvc/filters/addrequestparameter.html

Related dependency versions:

id 'org.springframework.boot' version '3.3.1'
implementation 'org.springframework.cloud:spring-cloud-starter-gateway-mvc'

I tried creating a bean, but don't understand how to obtain the value for addRequestParameter dynamically and I'm not sure about rewritePath either.

Example

File: com/example/demo/routes/RouteConfiguration.java

@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterAddRequestParam() {
        return route("add_request_parameter_route")
                .GET("v1/resource-name/id12345/methodName", http("https://example.org"))
                .before(
                        rewritePath("v1/resource-name/(?<segment>.*)", "v1/resource-name/methodName")
                                .andThen(addRequestParameter("id", "id12345"))
                )
                .build();
    }
}

1 Answer 1

0

have a look at https://www.baeldung.com/spring-cloud-gateway-url-rewriting. you can define a filter at RouteLocatorBuilder. Inside the filter you get the ServerHttpRequest where you can mutate the path as you needed it.

1
  • Thanks, but isn't RouteLocatorBuilder only for the Reactive API Gateway? I tried to use it, but could't resolve any of the imports. I would need to know a soution that works for Spring Cloud API Gateway (MVC) Commented Jun 24 at 23:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.