Convert GET to POST Inline with Java and Spring Gateway
You have a third-party provider that you need to obtain news information from and the only API they have for this is a POST with a request body, yet this clearly should be a GET process since the API is simply retrieving data and nothing transactional is happening.
You have a third-party provider that you need to obtain news information from.
The only API they have for this is a POST with a request body, yet this clearly should be a GET process since the API is simply retrieving data and nothing transactional is happening.
You are trying to keep your internal APIs as standard as possible and so would like the front-end to request this data as a GET with query parameters. If you are using Java and a Spring gateway, one solution is to receive the GET from the front-end and convert it to a POST inline prior to reaching out to the provider with the request.
We can make use of a request decorator in a gateway filter to alter the original request. This decorator extends ServerHttpRequestDecorator which wraps another ServerHttpRequest and delegates all methods to it. Subclasses can override specific methods selectively. We are overriding the getMethodValue and getURI methods. We override the getMethodValue method to return HttpMethod.POST.name() and we override the getURI method to remove the query parameters from the request.
We still have the request body to deal with. In our route definition, we apply the filter above before modifying the request body to ensure that any new headers we added in the filter are preserved. You can use the ModifyRequestBody filter to modify the request body before it is sent downstream by the gateway.
We use the NewsBody class to convert the query parameters into a json string suitable for a request body.
Full route example:
We have successfully received a GET from our front-end and converted it to a POST for our provider. Spring gateway offers many built-in gateway filters for adjusting requests and responses like Retry GatewayFilter Factory and JsonToGrpc GatewayFilter Factory.