Nuxtstop

For all things nuxt.js

Converting path params to query params in Spring Cloud Gateway

5 0

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}&"))
Enter fullscreen mode Exit fullscreen mode

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}&"))
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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