Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 14, 2022 05:21 pm GMT

Converting path params to query params in Spring Cloud Gateway

Problem Statement

How can I convert path-params on the incoming request to query params for one of your APIs.

TL;DR

.filters(fs -> fs.rewritePath("/(?<country>.\\S+)/(?<locale>.\\S+)/v(?<version>\\d+)/my-endpoint(?<queryParams>.*)",                        "/api/v2/my-endpoint?locale=${locale}&country=${country}&"))

Solution

API evolution is part of Microservices based development. One of our APIs used to have locale and country as path params. As we were writing a new version of the same API, we decided to have those path-params passed on as query-params instead.

In order to support migration from old to the newer version we decided to add gateway between the clients and two versions of the API.

The challenge now becomes that the client will keep sending the locale and country information like before but we need to somehow convert those params before calling the newer version.

Surprisingly, we were able to do that with relative ease. All you need is the following FilterSpec being added to your route -

.filters(fs -> fs.rewritePath("/(?<country>.\\S+)/(?<locale>.\\S+)/v(?<version>\\d+)/my-endpoint(?<queryParams>.*)",                        "/api/v2/my-endpoint?locale=${locale}&country=${country}&"))

With that in place the our gateway is now able to route the request to both the versions of our API without any impact on the client. Here are some logs collected for the gateway application -

Incoming request http://localhost:8081/us/en/v1/my-endpoint?channel=WEB is routed to id: my-api-v2-/us/en/v1/my-endpoint, uri:http://localhost:8080/api/v2/my-endpoint?locale=en&country=us&?channel=WEB

The above log statement was generated by using the code available on this thread on StackOverFlow


Original Link: https://dev.to/amitmisra16/converting-path-params-to-query-params-in-spring-cloud-gateway-3mno

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To